I am trying to achieve a JQuery AJAX call to a controller action method that contains a complex object as a parameter.
I have read plenty blogs and tried several techniques learned from these. The key post on which I have constructed my best attempt code (below) is the stackoverflow post here .
I want to trigger an asynchronous post, invoked when the user tabs off a field [not a Form save post – as demonstrated in other examples I have found].
My intention is to:
Instantiate an object on the client [not the ViewModel which provides the type for the View];
Populate the object with data from several fields in the view;
Convert this object to JSON;
Call the controller action method using the jQuery.Ajax method, passing the JSON object.
The results will be returned as a JSON result; and data will be loaded into fields in the view depending on results returned.
The problems are:
If the action method is attributed with the HttpPost attribute, the controller Action method is not invoked (even though the AJAX call type is set to ‘POST’).
If the action method isattributed with HttpGet, the values of properties of the parameter are null
The ReadObject method throws the error: "Expecting element 'root' from namespace ''.. Encountered 'None' with name 'namespace'".
Hopefully someone can help. Thanks. Code below:
Client js file
var disputeKeyDataObj = {
"InvoiceNumber": "" + $.trim(this.value) + "",
"CustomerNumber": "" + $.trim($('#CustomerNumber').val()) + ""
};
var disputeKeyDataJSON = JSON.stringify(disputeHeadlineData);
$.ajax({
url: "/cnr/GetDataForInvoiceNumber",
type: "POST",
data: disputeKeyDataJSON,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: EnrichedDisputeKeyData(result)
});
Action Filter and class for the type associated with the Action method parameter
[DataContract]
public class DisputeKeyData
{
[DataMember(Name = "InvoiceNumber")]
public string InvoiceNumber { get; set; }
[DataMember(Name = "CustomerNumber")]
public string CustomerNumber { get; set; }
}
Action method on the controller
//[HttpPost]
[ObjectFilter(Param = "disputeKeyData", RootType = typeof(DisputeKeyData))]
public ActionResult GetDataForInvoiceNumber(DisputeKeyData disputeKeyData)
{
//Blah!
//....
return Json(disputeKeyData, JsonRequestBehavior.AllowGet);
}
Below is how I got this working.
The Key point was:
I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
Related
I'm not sure to why the controller is receiving a data from an Ajax call . Could i be doing anything wrong?
[HttpPost]
[Route("Product/UpdateDetails")]
public ActionResult UpdateProduct (ProductModel model) <<// model here is null
{
Product p = new Product
{
ProductId = p.ProductId,
Price = p.Price,
};
return View("_ProductDetail"); }
Ajax call below:
var model = {
ProductId: 1,
Price: 270.99,
};
var json = JSON.stringify(model)
$.ajax({
url: '/Product/UpdateDetails',
type: 'Post',
contentType: "application/json; charset=utf-8",
model: model,
success: function (results) {
}
});
//Model
public class Product
{
public int Id {get;set;}
public double Price {get;set;}
}
Can you guys spot anything that i may be doing wrong in the code above ? I can't see anything that i'm doing wrong.
Try this:
$.ajax({
url: '/Product/UpdateDetails',
type: 'Post',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
You used JSON.Stringify() on your model, but forgot to use the variable "json" on the ajax call, so the ajax was trying to post a "non-json" model.
Also, there is no model setting in ajax calls, the correct one to post your data is data, as you can see here.
I am trying to post an object from jquery to MVC controller. The object is passed successfully but all the properties are null (or false for bools).
fwiw, if I JSON.stringify myObect then it does not pass at all, theObect in the controller is null.
I am using MVC4, .net 4.5, jQuery 1.9.1
Any help appreciate.
jQuery function
var myObject =
{
Property1: true,
Proerty2: true
};
$.ajax({
type: 'POST',
url: '/myController/StartProcess/',
data: { theObject: myObject }
});
Controller
private async void StartProcess(myObject theObject)
{
// theObect can be seen successfully but property1 and property2 are false
// if I change them to strings they are null
...
}
Class
public class myObject
{
public bool Property1 { get; set; }
public bool Property2 { get; set; }
}
EDIT:
The solution was:
$.ajax({
type: 'POST',
url: '/myController/StartProcess/',
data: myObject
});
If anyone can shed some light as to why this works and nothing else does it would be greatly appreciated. It is not a great solution because I have to put all my parameters in myObject, I cannot pass any additional parameters using this technique. also curious as to why all the info I find online, including official tutorials, say to use data: JSON.Strinify(myObect) but for me this causes all the properties of myObject to be null (or false).
Thanks to Roar all the same, at least I can move past this.
Get this JSON library and stringify() the object like this:
$.ajax({
type: 'POST',
url: '/myController/StartProcess/',
data: JSON.stringify(myObject)
});
try this
$.ajax({
type: 'POST',
url: '/myController/StartProcess/',
data: myObject
});
If you tried to POST your object to an API controller, it would probably work. I had some trouble with this myself. If you're using jQuery, you need to specify that you're sending JSON so the MVC controller will correctly interpret the data.
You could try this:
$.ajax({
contentType: 'application/json',
data: { theObject: myObject },
dataType: 'json',
type: 'POST',
url: '/myController/StartProcess/'
});
Here's what can also make all properties null :
public ActionResult GetPaymentView(CardModel Card)
{
}
If the view is a collection of a model, when you pass a serialized form of one element in the collection to ajax call, the controller expects the same name instance as the class name. I assume that this is the same way without collection but never tried. In this code example we serialize one element of the collection
$.ajax({
url: '/Shipments/GetPaymentView',
type: 'POST',
data: $('#' + ID).serialize(),
success: { onSuccess(); },
error: { onError(jqXHR, textStatus, errorThrown); }
});
The reason why this happens is because the view model is a collection of the CardModel and the serialization is adding CardModel before each properties like this : CardModel.ID=foo&CardModel.bar The model binder takes it as granted and tries to match the instance sent with the property of the controller which it can't and instantiate a new instance for you hence all properties are nulls.
Try adding contentType: "application/json; charset=utf-8" to your ajax call.
OK, finally figured it out. Here is a full and proper solution showing how to pass additional parameters along with the object:
jQuery:
var myString= "my paramter";
var myObject =
{
Property1: true,
Property2: true
};
var DTO = { param1: myString, param2: myObject };
$.ajax({
contentType: "application/json; charset=utf-8",
type: 'POST',
url: 'myController/StartProcess',
data: JSON.stringify(DTO)
});
Controller:
[HttpPost] // notice this additional attribute!
private async void StartProcess(string param1, myObject param2)
{
// param2 parameters are all true! param1 shows correctly too.
...
}
Class
public class myObject
{
public bool Property1 { get; set; }
public bool Property2 { get; set; }
}
I have a Kendo grid that has been sort-enabled. I want to do an ajax postback using jQuery to send the sort information to the action method to do some action.
var datasource = $(".data-table").data("kendoGrid").dataSource;
$.ajax({
type: 'POST',
url: '#Url.Action("ExportToPDf", "MyController")',
dataType: 'json',
data: { sort: datasource._sort }
});
I'm able to see with a debugger that the correct value is got and passed in the data attribute of the ajax. I used FireBug to confirm that the values are passed during the POST action.
public ActionResult ExportToPDf(List<SortDescription> sort)
{
//Will be doing some action
return null;
}
public class SortDescription
{
public string dir { get; set; }
public string field { get; set; }
}
Sample data from Firebug during POST action
sort[0][dir] asc
sort[0][field] EmployeeRef
When I keep breakpoint in action method, im able to get one item in the list, but the properties appear to be null.
Can anyone please guide me what I do wrong?
Try something like this:
$.ajax({
url: '#Url.Action("ExportToPDf", "MyController")',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({sort: datasource._sort })
})
Question is really simple. What is Request.InputStream and when to use it. Is it always used to read entire html body sent in the post request or only some parameters sent in it? Why should i not send data as a parameter to my server side code by passing it in the Ajax request?
In the example i can either pass the parameter in the data: or i can read the parameter in the Request.InputStream. When should i use which one?
Example:
In controller:
public ActionResult GetSomeData(string someData)
{
Request.InputStream.Position = 0;
System.IO.StreamReader str = new System.IO.StreamReader(Request.InputStream);
string sBuf = str.ReadToEnd();
return Json("something");
}
Ajax Request:
$.ajax({
type: "POST",
url: "Home/GetSomeData",
data: "{someData:'Hello'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
// Insert the returned HTML into the <div>.
$('#dvResult').html(msg);
}
});
Request.InputStream allows you to access the raw request data. If this data is formatted using some standard format such as application/x-www-form-urlencoded or multipart/form-data or some other format that the default model binder understands you do not need to use Request.InputStream. ASP.NET will parse the request values and you will be able to access them directly using Request[...]. Of course in ASP.NET MVC you don't even need to use Request[...] because you can define a view model which your controller action will take as parameter and leave the model binder assign its properties from the request.
There are cases though when you might want to access the raw request stream. For example you have invented some custom protocol and the client sends some custom formatted data in the request stream. Those cases are very rare since inventing custom protocols is not very common.
Now back to your question. In your case you could define a view model:
public class MyViewModel
{
public string SomeData { get; set; }
}
which your controller action will take as argument:
public ActionResult GetSomeData(MyViewModel model)
{
// model.SomeData will contain the Hello string that the client sent
return Json("something");
}
and on the client I would recommend you using the JSON.stringify method which is natively built into modern browsers to JSON serialize the request javascript literal into a JSON string instead of manually writing the JSON as you did:
$.ajax({
type: 'POST',
url: 'Home/GetSomeData',
data: JSON.stringify({ someData: 'Hello' }),
contentType: 'application/json; charset=utf-8',
success: function (msg) {
alert(msg);
// Insert the returned HTML into the <div>.
$('#dvResult').html(msg);
}
});
In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
//data: ??????
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
Every time there is a post, I need to increment the value attribute in the model:
public ActionResult Modelpage(MyModel model)
{
model.value = model.value + 1;
return PartialView("ModelPartialView", this.ViewData);
}
But the model is not passed to the controller when the page is posted with jQuery AJAX request. How can I send the model in the AJAX request?
The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.
For example, the Javascript:
var values =
{
"Name": "Chris",
"Color": "Green"
}
$.post("#Url.Action("Update")",values,function(data)
{
// do stuff;
});
The model:
public class UserModel
{
public string Name { get;set; }
public string Color { get;set; }
public IEnumerable<string> Contacts { get;set; }
}
The controller:
public ActionResult Update(UserModel model)
{
// do something with the model
return Json(new { success = true });
}
If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.
In our app, we do this with an extension method:
public static class JsonExtensions
{
public static string ToJson(this Object obj)
{
return new JavaScriptSerializer().Serialize(obj);
}
}
On the view, we use it to render the model:
<script type="javascript">
var model = <%= Model.ToJson() %>
</script>
You can then pass the model variable into your $.ajax call.
I have an MVC page that submits JSON of selected values from a group of radio buttons.
I use:
var dataArray = $.makeArray($("input[type=radio]").serializeArray());
To make an array of their names and values. Then I convert it to JSON with:
var json = $.toJSON(dataArray)
and then post it with jQuery's ajax() to the MVC controller
$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json,
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});
Which sends the data across as native JSON data.
You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.
To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.
Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.
Article on MVC JSON deserialization
This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.
I am achieving this either by a double click event on a grid row or click event on a button of some sort.
#model TestProject.Models.TestModel
<script>
function testButton_Click(){
var javaModel ={
ModelId: '#Model.TestId',
CreatedDate: '#Model.CreatedDate.ToShortDateString()',
TestDescription: '#Model.TestDescription',
//Here I am using a Kendo editor and I want to bind the text value to my javascript
//object. This may be different for you depending on what controls you use.
TestStatus: ($('#StatusTextBox'))[0].value,
TestType: '#Model.TestType'
}
//Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox
//selected value. This puzzled me due to the conversion to Json object in the Ajax call.
//By parsing the Type to an int this worked.
javaModel.TestType = parseInt(javaModel.TestType);
$.ajax({
//This is where you want to post to.
url:'#Url.Action("TestModelUpdate","TestController")',
async:true,
type:"POST",
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(javaModel)
});
}
</script>
//This is your controller action on the server, and it will autobind your values
//to the newTestModel on post.
[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
TestModel.UpdateTestModel(newTestModel);
return //do some return action;
}
I think you need to explicitly pass the data attribute. One way to do this is to use the
data = $('#your-form-id').serialize();
This post may be helpful.
Post with jquery and ajax
Have a look at the doc here..
Ajax serialize
you can create a variable and send to ajax.
var m = { "Value": #Model.Value }
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
data: m,
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
All of model's field must bo ceated in m.
In ajax call mention-
data:MakeModel(),
use the below function to bind data to model
function MakeModel() {
var MyModel = {};
MyModel.value = $('#input element id').val() or your value;
return JSON.stringify(MyModel);
}
Attach [HttpPost] attribute to your controller action
on POST this data will get available