How to get textbox value in Action in asp.net MVC 5 - asp.net-mvc-5

I want to send the value of textbox to the Action Method for searching the technology for that i want to get the value of textbox in Action.
I have the following code :-
#Html.TextBox("technologyNameBox", "", new { id = "technologyName", #class = "form-control", #placeholder = "Search For Technology" })
<span class="input-group-btn" style="text-align:left">
<a class="btn btn-default" id="searchTechnology"
href="#Url.Action("SearchTechnology", "Technology",
new {technologyName="technologyName",projectId=ProjectId })">
<span class="glyphicon glyphicon-search "></span>
</a>
</span>
Question :- How to get the value of textbox "technologyNameBox" in Action ?
Please help me out. Thanks in Advance!

You'd have to append the value to the URL via JavaScript before directing the user. Using jQuery (since that generally comes packaged with ASP.NET), it might look something like this (with a good bit of manual conditional checks for blank values or query string parameters):
$('#searchTechnology').click(function (e) {
e.preventDefault();
var url = '#Url.Action("SearchTechnology", "Technology", new { projectId=ProjectId })';
var technologyName = $('#technologyName').val();
if (technologyName.length < 1) {
// no value was entered, don't modify the url
window.location.href = url;
} else {
// a value was entered, add it to the url
if (url.indexOf('?') >= 0) {
// this is not the first query string parameter
window.location.href = url + '&technologyName=' + technologyName;
} else {
// this is the first query string parameter
window.location.href = url + '?technologyName=' + technologyName;
}
}
return false;
});
The idea is that when the user clicks that link, you would fetch the value entered in the input and append it to the URL as a query string parameter. Then redirect the user to the new modified URL.

Related

How insert result of a Netlify function into the HTML web page whose form called the function (example: calculator)

Background:
I'm coming from the server-side world of Rails, and trying to figure out the Netlify static html + serverless functions approach to doing a few extremely basic landing page web apps which need a serverless function to insert data into an HTML page.
I'm trying to start with the simplest possible case of an HTML page with a form and a serverless function that returns a result back to the page. (e.g., no static site generators).
I have not found any Netlify tutorials that show how a HTML page can have a form that posts to a function which then returns the result of that function back into the same web page.
The simplest sample app I can think of is a page asks a question, the user POSTs their answer to a serverless function, and the same HTML page is updated with the result of the function... a trivial case being to display "your answer was X" above the form. (It is immaterial to me whether the actual page is rewritten again with the result string included, or the result string is dynamically inserted by somehow poking the string to the div, so long as the result string originates in a serverless function; integrating serverless functions results with HTML pages is what I'm trying to learn.)
In the code below a simple HTML page below displays a form, the form POSTs an answer to a javascript function check_answer.js, and the javascript function erases the current page and displays the string "Your answer was XXXX".
That was simple to do, and lots of tutorials show how to have a function accept a form post then return a result string to the browser (overwriting the prior page).
My question:
How can the serverless function insert the result string back into the original HTML page (at the div id="answer") instead of outputting the result to a blank page?
Current code:
# index.html
<html>
<head>
<title>A test form</title>
</head>
<body>
<div id="answer">
</div>
<p>How much is 1 + 3?</p>
<p>form using POST:</p>
<form method="post" name="calc 2" action="/.netlify/functions/check_answer" id="calcform2" data-netlify="true" >
<p>
<label for="my_answer">Answer:</label>
<input type="text" name="my_answer" id="my_answer">
<label for="my_comment">Comment:</label>
<input type="text" name="my_comment" id="my_comment">
</p>
<p>
<input type="submit">
</p>
</form>
</body>
</html>
# functions/check_answer.js
exports.handler = async event => {
console.log(event.queryStringParameters);
console.log(event);
console.log(event.body);
if (event.httpMethod == 'POST')
{
console.log('is POST');
var params = parseQuery(event.body);
console.log(params);
var answer_string = params['my_answer'];
}
else
{
console.log('is GET');
var answer_string = event.queryStringParameters.my_answer || 'empty'
};
return {
statusCode: 200,
body: `Your answer was ${answer_string}`,
}
}
// handle parsing form query aaaa=bbbbb&cccc=dddd into hash object
// from https://stackoverflow.com/a/13419367/597992
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}

Show the item hit content only when the search box is not empty

I have this in my algolia file for my jekyll site.
<script>
const search = instantsearch({
appId: '{{ site.algolia.application_id }}',
apiKey: '{{ site.algolia.search_only_api_key }}',
indexName: '{{ site.algolia.index_name }}',
searchParameters: {
restrictSearchableAttributes: [
'title',
'content'
],
facetFilters: ['type:post']
},
});
const hitTemplate = function(hit) {
let date = '';
if (hit.date) {
date = moment.unix(hit.date).format('L');
// date = moment.unix(hit.date).format('MMM Do YY');
modifiedDate = moment.unix(hit.last_modified_at).format('MMM Do YY');
}
const url = hit.url;
const title = hit._highlightResult.title.value;
const content = hit._highlightResult.html.value;
return `
<div class="post-list">
<span class="post-date-list-wrap">
<span class="post-date-list">${date}
<span class="post-title"> ${title} </span>
</span>
${content}
</div>
`;
}
const hitTemplateTrans = function(hit) {
let date = '';
if (hit.date) {
date = moment.unix(hit.date).format('MMM DD YYYY');
}
const url = hit.url;
const title = hit._highlightResult.title.value;
const content = hit._highlightResult.html.value;
return `
<div class="post-list">
<span class="post-date-list-wrap">
<span class="post-date-list">${date}
<span class="post-title"> ${title}</span>
</span>
</span>
</div>
`;
}
search.addWidget(
instantsearch.widgets.searchBox({
container: '#search-searchbar',
placeholder: 'search notes',
autofocus: true
})
);
search.addWidget(
instantsearch.widgets.hits({
container: '#search-hits',
templates: {
empty: 'No results',
item: hitTemplate
},
})
);
search.start();
</script>
Without typing anything in the search box I have the list of articles
with the excerpt, the short introduction of the article.
That's because I have ${content} to show the highlights when someone
types the search term.
That's fine and everything is working but... I don't want to show the contents of each item when the search box is empty.
If the search box is empty I would like to keep only the title and the date
but if the search box is not empty just show the title/date and the excerpt as it's usual.
It seems like an easy task but I'm stuck right now, I tried removed the content tag and put in the hit transformation function, but it doesn't work.
The instantsearch.js library has a function hook, called searchFunction, you can define when instanciating the library. That is called right before any search is performed. You can use it to check if the current query is empty or not, and adapt your layout based on this knowledge.
Here is a slightly edited script (irrelevant parts removed) that should let you do what you're looking for:
let additionalClass = '';
const search = instantsearch({
[…]
searchFunction: function(helper) {
if (helper.getState().query === '') {
additionalClass = 'post-item__empty-query';
} else {
additionalClass = '';
}
helper.search()
}
});
[…]
const hitTemplate = function(hit) {
return
`<div class="post-item ${additionalClass}">
[…]
</div>`
;
}
.post-item__empty-query .post-snippet {
display: none;
}
What it does is defining a global variable (additionalClass) that will be used in the hit template (added alongside item-post, at the root level).
Right before everysearch, we check if the query is empty. If so, we set additionalClass to item-post__empty_query. We also defined in CSS that when this class is applied, the content should be hidden.
All of that together makes the title + date displayed when no search is performed, and the content displayed only when an actual keyword is searched for.
Hope that helps,

Input multiple with tags without autoCompletion

I have two inputs.
I want the two inputs to have the same look and feel see below:
The first input use autocomplete and allows the user to select a list of terms => I use p:autocomplete (see Primefaces documentation on autocomplete)
This input works fine.
For the second input, I would like to have the same display but without any autocompletion : the user just enter a list of terms with no autocompletion at all.
I tried to have a fake autocomplete that return the value given by the user but it is too slow and the behaviour is not correct when the user quit the input.
Any idea is welcome.
After a quick look at the PrimeFaces javascript code of the autoComplete and a few hours experimenting with it, I came up with a solution. It involves overriding the bindKeyEvents and in it deciding to call the original one or not, adding detection for the space key ('selecting a tag') and when pressed, add the tag and fire the selectionEvent (if ajax is used). Place the following code in your page or in an external javascript file
<script>
//<![CDATA[
if(PrimeFaces.widget.AutoComplete) {
PrimeFaces.widget.AutoComplete = PrimeFaces.widget.AutoComplete.extend ( {
bindKeyEvents: function() {
if (this.input.attr('data-justTags')) {
var $this = this;
this.input.on('keyup.autoComplete', function(e) {
var keyCode = $.ui.keyCode,
key = e.which;
}).on('keydown.autoComplete', function(e) {
var keyCode = $.ui.keyCode;
$this.suppressInput = false;
switch(e.which) {
case keyCode.BACKSPACE:
if ($this.cfg.multiple && !$this.input.val().length) {
$this.removeItem(e, $(this).parent().prev());
e.preventDefault();
}
break;
case keyCode.SPACE:
if($this.cfg.multiple) {
var itemValue = $this.input.val();
var itemDisplayMarkup = '<li data-token-value="' +itemValue + '"class="ui-autocomplete-token ui-state-active ui-corner-all ui-helper-hidden">';
itemDisplayMarkup += '<span class="ui-autocomplete-token-icon ui-icon ui-icon-close" />';
itemDisplayMarkup += '<span class="ui-autocomplete-token-label">' + itemValue + '</span></li>';
$this.inputContainer.before(itemDisplayMarkup);
$this.multiItemContainer.children('.ui-helper-hidden').fadeIn();
$this.input.val('').focus();
$this.hinput.append('<option value="' + itemValue + '" selected="selected"></option>');
if($this.multiItemContainer.children('li.ui-autocomplete-token').length >= $this.cfg.selectLimit) {
$this.input.css('display', 'none').blur();
$this.disableDropdown();
}
$this.invokeItemSelectBehavior(e, itemValue);
}
break;
};
});
} else {
//console.log("Original bindEvents");
this._super();
}
}
});
}
//]]>
</script>
For deciding on when to call the original one or not, I decided to use a passThrough attribute with a data-justTags name. e.g. pt:data-justTags="true" (value does not matter, so pt:data-justTags="false" is identical to pt:data-justTags="true"). A small html snippet of this is:
<p:autoComplete pt:data-justTags="true" multiple="true" value="#{myBean.selectedValues}">
And do not forget to add the xmlns:pt="http://xmlns.jcp.org/jsf/passthrough" namespace declaration.
I found a component that could do the job : http://www.butterfaces.org/tags.jsf

Meteor Facebook Profile Picture not Displaying

On first sign I have the following code:
Accounts.onCreateUser(function(options,user){
if (typeof(user.services.facebook) != "undefined") {
user.services.facebook.picture = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=large";
}
return user;
});
Which results in the following URL string
http://graph.facebook.com/[myfacebookid]/picture/?type=large
Yet when it renders that url and returns
<img scr="http://graph.facebook.com/[myfacebookid]/picture/?type=large" alt="My Name">
All I see is a broken image. How can I pull this in so that it renders the facebook profile picture?
I use a helper function based off of the Facebook ID of the user to grab the image on the server. I notice my url has /picture? and your has /picture/? Hope this helps.
userPicHelper: function() {
if (this.profile) {
var id = this.profile.facebookId;
var img = 'http://graph.facebook.com/' + id + '/picture?type=square&height=160&width=160';
return img;
}
},
I don't know how I missed this before, but is this the src attribute on the image tag is actually written as scr:
<img scr=
Should be...
<img src=
You have http instead of https.
So:
"https://graph.facebook.com/" + id + "/picture/?type=large";
This was my problem.

Opencart 1.5.4 Search by Description

I have read various entries about searching by description and subcategories in opencart by default but I have a unique problem. I have two header files because my site has 2 headers... one for the home page and one for every other page.
Home Page:
https://garrysun.com/
Other Page:
https://garrysun.com/ayurveda-products/categories
When I search on the home page I get the correct results (search the word "heart") but when I search any other page it doesn't return the search for descriptions or subcategories.
Home Page Search Results:https://garrysun.com/index.php?route=product/search&filter_description=true&filter_sub_category=true&filter_name=heart
Other Page Search Results:https://garrysun.com/index.php?route=product/search&filter_name=heart
As you can see, when I search the other page the extra code is not being added to search in descriptions and subcategories.
So why is this new code that I added working for the home page an not any other page?
To make this search function work I have changed the common.js file to look like this (adding the two lines below each "url= $(base..." section:
/* Search */
$('.button-search').bind('click', function() {
url = $('base').attr('href') + 'index.php?route=product/search';
url += '&filter_description=true'; // ADDED this to search descriptions
url += '&filter_sub_category=true'; // ADDED this to search sub-categories
var filter_name = $('input[name=\'filter_name\']').attr('value');
if (filter_name) {
url += '&filter_name=' + encodeURIComponent(filter_name) ;
}
location = url;
});
$('#header input[name=\'filter_name\']').bind('keydown', function(e) {
if (e.keyCode == 13) {
url = $('base').attr('href') + 'index.php?route=product/search';
url += '&filter_description=true'; // ADDED this to search descriptions
url += '&filter_sub_category=true'; // ADDED this to search sub-categories
var filter_name = $('input[name=\'filter_name\']').attr('value');
if (filter_name) {
url += '&filter_name=' + encodeURIComponent(filter_name) ;
}
location = url;
}
});
Both header files use the same code to call the search function:
<div id="search">
<div class="button-search"></div>
<?php if ($filter_name) { ?>
<input type="text" name="filter_name" value="<?php echo $filter_name; ?>" />
<?php } else { ?>
<input type="text" name="filter_name" value="<?php echo $text_search; ?>" onclick="this.value = '';" onkeydown="this.style.color = '#000000';" />
<?php } ?>
</div>
</div>
After trying to figure out what's wrong in your code for few minutes (unsuccessfully), I ran a network debugging and found out that nothing is wrong with your code, you are just calling 2 different Javascript files(!):
On your home page, you are using common.js that is located at https://garrysun.com/catalog/view/javascript/common.js.
On your category pages, you are using common.js that is located at https://garrysun.com/catalog/view/javascript/add2cart-go2cart/common.js.
The 2nd one does not include your modifications, and looks like this:
$('.button-search').bind('click', function() {
url = $('base').attr('href') + 'index.php?route=product/search';
var filter_name = $('input[name=\'filter_name\']').attr('value');
if (filter_name) {
url += '&filter_name=' + encodeURIComponent(filter_name);
}
location = url;
});
$('#header input[name=\'filter_name\']').bind('keydown', function(e) {
if (e.keyCode == 13) {
url = $('base').attr('href') + 'index.php?route=product/search';
var filter_name = $('input[name=\'filter_name\']').attr('value');
if (filter_name) {
url += '&filter_name=' + encodeURIComponent(filter_name);
}
location = url;
}
});
Vuala.
Hope this helps!

Resources