How to pass two data model from view to controller using jquery Ajax

Johnson picture Johnson · Feb 9, 2016 · Viewed 10.8k times · Source

I am developing web application using MVC. In one case, I am going to use a jquery ajax method to call server side action from my view. I have to pass two model object as a data for ajax, but every time it passes the null values. I referred Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view for solve my problem, but doesn't satisfied. So how can I pass my model object using jquery ajax?

Jquery code for calling Action

 $("#btnAddAjax").click(function(e){
                e.preventDefault();


                var usermodel = {
                    US_FirstName:$("#txtFirstName").val(),
                    US_LaststName:$("#txtFirstName").val()
                };
                var citydatemodel = {
                    date:$("#SignDate").val(),
                    city: $("#selectCity").val()
                };


                $.ajax({
                    url:'@Url.Action("AllLandLord")',
                    contentType:'application/json; charset=utf-8',

                    data: JSON.stringify({User: usermodel, testM: citydatemodel}),
                    UpdateTargetId: "dvLandLord3",
                    type:'POST',
                    success:function(data){
                        $("#dvLandLord3").html(data);
                    },
                    error:function(){
                        alert('Something Wrong !!!');
                    }
                });
            });

I have two models, for this purpose I am calling this from viewModel

    public class User_Master
    {
      [Required(ErrorMessage = "* Please Enter First Name For Tenant")]
       public string TN_FirstName { get; set; }

      [Required(ErrorMessage = "* Please Enter Last Name For Tenant")]
       public string TN_LastName { get; set; }  
    }


public partial class CityDate
{
    [Required(ErrorMessage = "* Please Select Your City.")]
    public string PR_City { get; set; }

    [Required(ErrorMessage = "* Please Select Date")]
    public Nullable<System.DateTime> CM_AgreementSignDate { get; set; }
}

And finally, I am going to call following action(which is for partial view) with jquery ajax.

[HttpPost]
    public PartialViewResult AllLandLord(User_Master usermaster, CityDate citydate)
    {
        List<User_Master> allLandLord = new List<User_Master>();
        if (ModelState.IsValid)
        {
            allLandLord = agreementnewBAL.AllLandLordUsers();
            return PartialView("LoadLandLord", allLandLord);
        }
        else
        {
            return PartialView("LoadLandLord", allLandLord);
        }
    }

Answer

Jay picture Jay · Feb 9, 2016

I put together a quick demo:

a basic action:

[HttpPost]
public ActionResult TestMethod(userModel User, testModel testM)
{
    return View();
}

The models:

public class testModel
{
    public string UserType { get; set; }
}

 public class userModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

my javqascript:

 <script type="text/javascript">
    $("#myButton").click(function () {
        var usermodel = {
            FirstName: 'testfn',
            LastName: 'testln'
        }

        var testmodel = {
            UserType: 'test'
        }

        $.ajax({
            url: '@Url.Action("TestMethod")',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({User: usermodel, testM: testmodel}), 
            type: "POST",
            success:function(data){
                alert("success");
            },
            error: function(){
                alert("error");
            }
        });
    });
</script>

calling that JS results in the data I assign being passed to the action correctly.

You should be able to just update my JS code to get it working in your project.

EDIT: The data: component of your ajax call needs to match your controller

data: JSON.stringify({User: usermodel, testM: testmodel}),

from my example becomes

data: JSON.stringify({usermaster: usermodel, citydata: citydatamodel}),

Edit 2:

You also need to make sure your js models match your MVC models:

var usermodel = {
   US_FirstName:$("#txtFirstName").val(),
   US_LaststName:$("#txtFirstName").val()
};
var citydatemodel = {
    date:$("#SignDate").val(),
    city: $("#selectCity").val()
};

These don't match your MVC models.

var usermodel = {
   TN_FirstName:$("#txtFirstName").val(),
   TN_LaststName:$("#txtFirstName").val()
};
var citydatemodel = {
    CM_AgreementSignData:$("#SignDate").val(),
    PR_City: $("#selectCity").val()
};