I am trying to get jQuery autocomplete in a textbox. But I don't seem to be able to display the data from my JsonResult in the view, I checked with firebug and verfied that the data is transferred from server, just doesn't disply in the TextBox. I don't get any errors.
Here's my code :
public JsonResult search(string term)
{
// string prefixText =SearchString;
var FamilyLastName = _repository.FamilySearch(term);
var data=FamilyLastName.ToList();
return Json(data);//.Select(x => new { label = x, ID = x }));
}
#using (Html.BeginForm())
{
<label for="SearchString">My Autocomplete:</label>
<input class="form-control" type="text" name="SearchString" id="SearchString" autocomplete="off" />
}
<script type="text/javascript">
$(document).ready(function () {
var param = { "searchstring": $("#SearchString").val() };
$("#SearchString").autocomplete({
autoFocus: true,
source: function (request, response) {
// call your Action
$.ajax({
url:'search?term=' + $("#SearchString").val(),
// data:"{'term':'" +$("#SearchString").val() + "'}",
dataType: 'json',
method: "post",
contentType: "application/json; charset=utf-8",
success: function (data) {
return{
label:data.FamilyLastName
};
},
select:
function (event, ui) {
$('#SearchString').val(ui.item.label);
return false;
},
});
},
minLength: 1,// requ
Related
I am trying to make an autocomplete functionality for my page.
I have a textbox and I would like to make suggestions from my database.
I have this JsonResult in my controller:
public JsonResult ItemAutocomplete(string term)
{
var result = _db.SelectTable("SELECT [i].[Name] from [dbo].[Item][i] WHERE [i].[Name] LIKE #0", SqlDb.Params(term +"%"));
return Json(result, JsonRequestBehavior.AllowGet);
}
and in my view:
#Scripts.Render("~/bundles/jqueryui")
<h2>jQuery AutoComplete</h2>
<script>
$(function () {
$('#tags').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("ItemAutocomplete")',
extraParams: { term: $('#tags').val(),
dataType: "json",
contentType: 'application/json, charset=utf-8',
data: {
term: $("#tags").val()
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
The problem is that my ItemAutocomplete jsonResult always receives a null param... even if I call it directly from localhost, like this: "localhost/Appointment/ItemAutocomplete/item1".
Use (request.term) below
data: { term: request.term }
instead of
data: { term: $('#tags').val() }
In Autocomplete Text box, search string detect by "request.term".
I am building a website online store I want when click the add to cart button then number of commodity to be stored in a session with ajax and the message "saved" is displayed But this don’t work and don't display "saved"
View :
<p>
<img src="images/a.jpg">
<input type="text" id="1232542">
<button class="art-button">add to cart</button></p><p id="resolt">
</p>
jQuery :
$('#btntaeid1').click(function () {
var number = $("#1232542").val();
$("#resolt").html('loding...');
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Main", "AddToCart")',
data: { 'Number': number },
success: function(aaaa) {
$("#resolt").html(saved);
}
});
});
Session class
public class SessionCommodity
{
private string NumberCommodity;
public SessionCommodity()
{
}
}
AddToCart Action in Main controler
[HttpPost]
public ActionResult AddToCart(int Number)
{
var s = System.Web.HttpContext.Current.Session["cart"] as List<SessionCommodity>;
if (s == null)
{
System.Web.HttpContext.Current.Session["cart"] = s;
}
s.Add(new SessionCommodity {NumberCommodity = Number });
return Json(new {Added = true});
}
You are trying to call the ajax method when the button which has id of "btntaeid1" clicked. But your html content hasnt got that element. Either add the id attribute to the button element or change the click function to be fired when something exist is clicked.
View:
<p>
<img src="images/a.jpg">
<input type="text" id="1232542">
<button id="btntaeid1" class="art-button">add to cart</button></p><p id="resolt">
</p>
or the jquery part according to your post:
$('.art-button').click(function () {
var number = $("#1232542").val();
$("#resolt").html('loding...');
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Main", "AddToCart")',
data: { 'Number': number },
success: function(aaaa) {
$("#resolt").html(saved);
}
});
});
Ajax post:
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
// var vals = [];
// $('input:checkbox[name=Blanks]:checked').each(function () {
// vals.push($(this).val());
// });
// alert(vals);
//
var checkboxData = $(':checked').val();
$.ajax({
// Check the value.
type: 'POST',
url: '/Home/Extract',
data: { 'name': checkboxData },
// contentType: 'application/json; charset=utf-8', // No need to define contentType
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
});
Controller method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Extract(string[] name)
{
}
My problem is that I am getting null values in my string[] name when I use array and single checkBox values when I use other case. Any suggestions or ideas as to why the post looks good?
View:
<input type="button" id="btn" value="Extract" style="float:right "/>
#foreach (var m in (List<string>)ViewData["list"])
{
<ul>
<li>
<input type="checkbox" class="myCheckbox" name="Blanks" id="chk" value="#m"/>
<img src="#m" alt=""/>
First start by fixing your markup and remove the id="chk" from your checkboxes because you cannot have 2 elements with the same id.
Alright, and then simply generate a javascript array containing the values of the selected checkboxes and POST this array to the server:
$('#btn').click(function () {
var values = $('input[type="checkbox"].myCheckbox:checked').map(function() {
return $(this).val();
}).toArray();
$.ajax({
type: 'POST',
url: '/Home/Extract',
data: JSON.stringify({ name: values }),
contentType: 'application/json',
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
return false;
});
And your controller action signature might look like this:
[HttpPost]
public ActionResult Extract(string[] name)
{
...
}
But all this would have been completely unnecessary if you had used a view model and the strongly typed Html.CheckBoxFor helper.
I have an Action Method that returns a JSON-serialized object. The problem I'm having is that the JSON returned is opening in a new page, instead of being processed by the "success" function of the jquery.Ajax method.
Here's the controller action:
[HttpPost]
public ActionResult AddAssignment(AssignmentViewModel avm)
{
db.Assignments.Add(new Assignment
{
Name = avm.Name,
DueDate = DateTime.Parse(avm.DueDate),
CourseID = avm.CourseID,
IsComplete = false
});
db.SaveChanges();
avm.Course = db.Courses
.Where(x => x.CourseID == avm.CourseID)
.SingleOrDefault()
.Name;
return Json(avm);
}
Here's the View (form):
#model Fooburg.Mvc.Models.AssignmentViewModel
<h2 style="margin: 0 0 24px 0">Add Assignment:</h2>
#using (Html.BeginForm("AddAssignment",
"Assignments",
FormMethod.Post,
new { #id = "add-assignment-form" }))
{
<dl class="tabular">
<dt>Course:</dt>
<dd>
#Html.DropDownListFor(x => x.CourseID, new SelectList(ViewBag.Courses, "CourseID", "Name"))
</dd>
<dt>Assignment:</dt>
<dd>
#Html.TextBoxFor(x => x.Name)
</dd>
<dt>Due Date:</dt>
<dd>
#Html.TextBoxFor(x => x.DueDate, new { #class = "date" })
<script type="text/javascript">
$(function () {
$('.date').datepicker({ dateFormat: "mm/dd/yy" });
});
</script>
</dd>
</dl>
<p>
<input type="submit" value="Add Assignment" id="new-assignment-submit" />
</p>
}
And here's the javascript:
$(function () {
$('#add-assignment-form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
});
});
I have tried the event.stopPropogation() method, but didn't change my problem
EDIT: I've updated my javascript to the following, but I'm still getting the same result
$('#add-assignment-form').submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
You need to return false; or event.preventDefault() to prevent the browser from submitting the form normally.
You have two options here,
Use Ajax.BeginForm() instead of Html.BeginForm() that you would use like
#using(Ajax.BeginForm( "AddAssignment", "Assignments",
new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "output"})) {
...
}
and get rid of the javascript code.
Or call event.prevendDefault() in
$('#add-assignment-form').submit(function (event) {
// ...
event.preventDefault();
});
Just specify
return false;
after your $.ajax() call
UPDATE
$(function () {
$('#add-assignment-form input[type=submit]').click(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
});
Have you checked if there are other javascript errors on the page that might be causing this unexpected behaviour? I would suggest Firebug for FF or Javascript Console for Chrome.
Also, I've noticed that sometime FF has issues if you don't specify the script type, so make sure your type is set to "text/javascript".
hth,
-covo
Can I post to action from view a filed of of my model ? Is is not part of the form. I just want to pass the myModel.someValue as argument to nextRelease action, hopefully without putting it anywhere in the form.
e.g.
View:
#model myModel
#using (Html.BeginForm("Search", "News", FormMethod.Get, new { id = "myform" }))
{
<div>myModel.someValue</div> //to show it has this field
<script type="text/javascript">
$('#nextbutton').click(function () {
$('#myform').attr("action", "/#controller.Language/news/nextRelease");
$("#submit").click();
});
</script>
}
Sure, you could use AJAX:
#model myModel
<script type="text/javascript">
$(function() {
$('#nextbutton').click(function () {
var url = '#Url.Action("NextRelease", "News")';
var dataToPost = #Html.Raw(Json.Encode(new { someValue = Model.SomeValue }));
$.post(url, dataToPost, function(result) {
alert('data successfully posted to server');
});
return false;
});
});
</script>
<button id="nextbutton">Next button</button>
or if you wanted to post not only a single property but the entire model:
var url = '#Url.Action("NextRelease", "News")';
var dataToPost = #Html.Raw(Json.Encode(Model));
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(dataToPost),
success: function(result) {
alert('data successfully posted to server');
}
});