Send view model from ajax to controller

Is it possible to create an object in a view and send it to the controller via ajax?

using

$.ajax({ type: "POST", etc.... 

??? I want to send an object of the type that I get in the view, in the form

 @model Project1.ViewModels.ModelSample 
+6
source share
3 answers

maybe

It is beautiful (and easy) possible.

What about complex objects?

@xixonia provided all the information you may need for this. But these examples are quite simple and may not provide information if you have any complex objects:

 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 one level of properties in its tree is considered to be a complex object. Using the method provided by @xixonia will not work in this case .

So, if you want to use such a scenario as well, I suggest you read this blog post that describes the whole problem in detail as well as provides a fairly simple jQuery plugin that allows you to send even complex objects to Asp.net MVC controller actions that will be bound to your independent complex strong type.

Other posts on the same blog may also be helpful:

If you use Ajax along Asp.net MVC, you will find these posts very helpful and save most of your development time when you encounter such problems.

+9
source

So 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 }); } 
+4
source

Is it possible to create an object in view and send it to the controller via ajax?

That's right. You can use ASP.NET MVC model bindings for this.

 var data = { Id: 5, Value: "Hello, world!" }; $.post('Home/MyAction', data); 

And you should have the appropriate POCO:

 public class MyPoco { public int Id { get; set; } public string Value { get; set; } } 

And the action that binds your model:

 public ActionResult MyAction(MyPoco myPoco) { if(ModelState.IsValid) { // Do stuff } } 

This should automatically deserialize your request into POCO.

+3
source

Source: https://habr.com/ru/post/886284/


All Articles