2

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);
        }
    }
Community
  • 1
  • 1
Johnson
  • 45
  • 1
  • 1
  • 7

1 Answers1

0

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()
};
Jay
  • 2,077
  • 5
  • 24
  • 39
  • OK Jay, I'll try this – Johnson Feb 09 '16 at 13:17
  • Hello Jay, Nice solution but this not worked for me. Is there any different way to implement this? – Johnson Feb 09 '16 at 13:28
  • edited my answer, you need to make your data: line match your controller param names – Jay Feb 09 '16 at 13:41
  • I used `data: JSON.stringify({usermaster: usermodel, citydata: citydatamodel}),` , but it does not executed – Johnson Feb 09 '16 at 13:46
  • spotted another problem with your code, made an edit to my answer. for the JSON binding to work, the variable names in JSON have to match the property names in your model. – Jay Feb 09 '16 at 13:53
  • Hello Jay, It was my spelling mistake at `usermaster` in declaration, It's working now. I checked using debugger, But It sends only firstName to action other parameters are still `null`. – Johnson Feb 09 '16 at 13:53
  • Perfect. As your suggestion, I matched variable name and property name which results into correct answer. Thank you so much. – Johnson Feb 09 '16 at 13:59