Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send a view model from ajax to controller

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
like image 206
bb2 Avatar asked Apr 20 '11 02:04

bb2


3 Answers

It's possible

This is perfectly (and easily) possible.

What about complex objects?

@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:

  • successfully model bind forms to IList<T> action parameters (or within complex type parameters)
  • handling validation errors with Ajax requests

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.

like image 123
Robert Koritnik Avatar answered Oct 24 '22 12:10

Robert Koritnik


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 });
}
like image 36
Sanchitos Avatar answered Oct 24 '22 11:10

Sanchitos


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.

like image 3
cwharris Avatar answered Oct 24 '22 11:10

cwharris