Is it possible to create an object in a view and send it to a controller through ajax?
using the
$.ajax({
type: "POST", etc....
??? I want to send an object of the type that I receive in the view as
@model Project1.ViewModels.ModelSample
This is perfectly (and easily) possible.
@xixonia provided all the information you may need to do so. But those examples are rather basic and may not provide information in case you have some sort of complex objects as:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public Person Spouse { get; set; }
public IList<Person> Children { get; set; }
}
Any object that has more than a single level of properties in its tree is regarded as a complex object. Using technique provided by @xixonia will fail to work in this case.
So if you'd like to also use this kind of scenario I suggest you read this blog post that describes the whole problem in detail as well as provides a rather simple jQuery plugin that makes it possible to send even complex objects to Asp.net MVC controller actions that will be model bound to your whatever complex strong type.
Other posts on the same blog may also prove to be helpful:
IList<T>
action parameters (or within complex type parameters)If you'll be using Ajax along Asp.net MVC you will find these posts very useful and will save you much of your development time when you run against such issues.
This is the way it worked for me:
$.post("/Controller/Action", $("#form").serialize(), function(json) {
// handle response
}, "json");
[HttpPost]
public ActionResult TV(MyModel id)
{
return Json(new { success = true });
}
Is it possible to create an object in a view and send it to a controller through ajax?
Absolutely. You can use ASP.NET MVC's model binding for this.
var data =
{
Id: 5,
Value: "Hello, world!"
};
$.post('Home/MyAction', data);
And you should have a matching POCO:
public class MyPoco
{
public int Id { get; set; }
public string Value { get; set; }
}
And an Action which takes your model to bind:
public ActionResult MyAction(MyPoco myPoco)
{
if(ModelState.IsValid)
{
// Do stuff
}
}
This should automatically deserialize your request into a POCO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With