In my c# mvc4 application I have three objects I wish to pass to an ActionResult using an AJAX post with Jquery. The objects are two strings and a form collection. Ive had no problems passing only the form collection, but cant seem to get the syntax correct for passing all three. Here is what Ive tried:
$(document).ready(function () {
$('#ChangeName').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
type: "POST",
data: {tdata + origname + newname},
url: "Home/ChangeName",
success: function (result) { success(result); }
});
});
Ive also tried commas after each variable name in the data: section with and without the brackets. How can I pass all three? When its been successful both string values have populated correctly when debugging but the values dont appear in the ActionResult and show null instead.
Ive also tried placing this below data: contentType: "application/x-www-form-urlencoded",
Here is the beginning of my ActionResult as well:
public ActionResult ChangeName(string Name, string updatedName, FormCollection mCollection)
Can you try:
$(document).ready(function () {
$('#ChangeName').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
Name: origname,
updatedName: newname
},
url: "Home/ChangeName",
success: function (result) { success(result); }
});
});
I think the problem is how you are putting the origname and newname in the ajax request.
Try this:
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
url: 'Home/ChangeName',
type: "POST",
data: $("#form1").serialize() + "&origname =" + origname + "&newname =" + newname,
success: function (result) { success(result); }
});
Related
I have a view with multiple inputs for my Model (Html.TextBoxFor(x => x.attribute) etc. And my ajax method is:
function callMethod() {
$.ajax({
type: "POST",
data: $('#Form').serialize() ,
url: '#Url.Action("formMethod", "Test")',
}).done(function (newTable) {
$('#RefundTableDiv').html(newTable);
});
};
and this works perfectly, the model comes perfectly to formMethod, but when i change formMethod and add another parameter for example 'int test' it doesnt work anymore.
My method looks like:
function callMethod() {
var number = 2;
$.ajax({
type: "POST",
data: {"model": $('#Form').serialize(),
"test": number},
url: '#Url.Action("formMethod", "Test")',
}).done(function (newTable) {
$('#RefundTableDiv').html(newTable);
});
};
the "test": number does come correctly to the method in the controller but the model suddenly is null now?
What am i doing wrong?
Using .serialize() serializes your model as a query string (e.g. someProperty=someValue&anotherProperty=anotherValue&...). To add additional name/value pairs, you can append then manually, for example
var data = $('#Form').serialize() + '&test=' + number;
$.ajax({
....
data: data;
or use the param() method (useful if you have multiple items and/or arrays to add)
var data = $("#Form").serialize() + '&' + $.param({ test: number }, true);
$.ajax({
....
data: data;
you can do it like this:
function callMethod() {
var number = 2;
var sd = $('#Form').serializeArray();
sd.push({ name:"test", value:number });
$.ajax({
type: "POST",
data: sd,
url: '#Url.Action("formMethod", "Test")',
}).done(function (newTable) {
$('#RefundTableDiv').html(newTable);
});
};
I am passing data to controller through Ajax call.
Following is the ajax code:
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List[i] = $(selectedItem).text();
});
var from_Month = $("#fromKPAMonthPicker").val();
var from_Year = $("#fromKPAYearPicker").val();
var to_Month = $("#toKPAMonthPicker").val();
var to_Year = $("#toKPAYearPicker").val();
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
success: function (data) {
$("#divList").html(data);
}
});
Controller action method:
[HttpPost]
public ActionResult _DataByFromTo(List<Int32> doj_Month_List, Int16 from_Month, Int16 from_Year, Int16 to_Month, Int16 to_Year)
{
return View();
}
It was working in my old code perfectly fine. I don't know whats the problem. because all data are passing perfectly except this array of jquery.
To disable deep serialization of objects you need to set traditional property to true.
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
traditional: true,
success: function (data) {
$("#divList").html(data);
}
});
When set to true it results in a shallow serialization.
Following link might be of help.
https://api.jquery.com/jQuery.param/
try using push
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List.push($(selectedItem).text());
});
I want to be able to post json data that was created via a javascript function through the Ajax.ActionLink helper.
I am able to accomplish this through straight jQuery code, but I am going to be doing this in a lot of places and wanted to see if there was a more efficient way to do it within MVC.
Working jQuery code:
$(function () {
$("#delete-selected").click(function () {
var ids= getSelected('ItemGrid'); //this returns a string[]
var postData = { Ids: courseIds };
var url = '/Home/DeleteSelected';
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'json',
data: postData
});
});
});
Write a script that uses unobtrusive JavaScript hooks like data- attributes to store the settings.
HTML:
<div data-ajax-url='/Home/DeleteSelected'
data-ajax-post-data='{function name or json content}'>
....
</div>
JQuery Plugin
$(document).on("click","[data-ajax-url]", function(){
var postData = $(this).data("ajax-post-data");
var url = $(this).data("ajax-url");
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'json',
data: postData
});
}
If you are doing an ajax call and want to update html with MVC, I would normally return Partial View from my call.Then update the html of the current holder with the result
Server Side
public ActionResult DeleteSelected(int[] Ids)
{
//do something
MyModel model = new Model(); //create object with new data
return Partial("_PartialViewName", model);
}
Javascript
$("#delete-selected").click(function () {
var ids= getSelected('ItemGrid'); //this returns a string[]
var postData = { Ids: courseIds };
var url = '/Home/DeleteSelected';
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'html',
data: postData
success: function(result){
$('#MyPartialViewContainer').html(result);
}
});
});
I post data to my aspx file qith the following code:
$.ajax({
type: 'POST',
url: "Ajax_Text.aspx?rand=" + myRand
+ "&id=" + $(".articleID").attr('title')
+ "&text=" + $("#text").val(),
cache: false,
beforeSend: function () {
},
success: function (data) {
alert(data);
}
});
Why i catch the text value by using the following code
string text = "";
if (!String.IsNullOrEmpty(Request.QueryString["text"]))
{
text = Request.QueryString["text"].ToString();
}
else
{
text = "";
}
and not this code:
string text = "";
if (!String.IsNullOrEmpty(Request.Form["text"]))
{
text = Request.Form["text"].ToString();
}
else
{
text = "";
}
Why is that? I expected Request.Form to work as i post data with jquery! Any ideas?
I suspect that the problem is that i have my input in the url parameter. Maybe i should put it to a data parameter but that means it will become a json request!
POST data are not send in query string but added to the request body. Try this code:
$.ajax({
type: 'POST',
url: "Ajax_Text.aspx",
data: {'rand': myRand, 'id': $(".articleID").attr('title'), 'text': $("#text").val()},
cache: false,
beforeSend: function () {
},
success: function (data) {
alert(data);
}
});
You are "posting" the data (text) as a query string (as part of URL) so you have to use Request.QueryString.
Why does this ajax error happen when I try post html in the string with stringify.
It looks like the stringify escapes the charactors automatically.
do I have to escape? thanks
var s;
//s = "my test test"; //if I post this it works
s = "my test test<br />"; //if I post this it break when I add the html
var a = { "myText": JSON.stringify(s) };
$.ajax({
type: "POST",
url: "test.aspx",
data: a,
success: function (data) {
//pass
},
error: function () {
alert("error");
}
});
then on the page load I'm trying to read the posted data with
HttpContext.Current.Request.Form("myText")
Try this:
var s = "my test test<br />",
a = { "myText": s };
a = JSON.stringify(a)
$.ajax({
type: "POST",
url: "test.aspx",
data: a,
success: function (data) {
//pass
},
error: function () {
alert("error");
}
});
You don't need to call JSON.stringify().
JSON.stringify is intended to serialize the object to JSON string, but you're passing a string to it and it's wrong.
Just pass the object with $.ajax() call:
var s = "my test test<br />";
.ajax({
type: "POST",
url: "test.aspx",
data: {
myText: s
},
success: function (data) {
//pass
},
error: function () {
alert("error");
}
});
Also jQuery documentation:
The data option can contain either a query string of the form
key1=value1&key2=value2, or a map of the form {key1: 'value1', key2:
'value2'}.
So in our particular example we used a "map" of the form, namely JavaScript object.