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);
        }
    }
6
  • could be because you are setting the content type to html in your ajax call. Have you tried removing that line, or specifying JSON? Commented Feb 9, 2016 at 12:15
  • If I use contentType to JSON. It gives error pop up. Commented Feb 9, 2016 at 12:23
  • what about if you remove that line? Commented Feb 9, 2016 at 12:24
  • When I reomve that line, It does not pass anything, null as usual. Commented Feb 9, 2016 at 12:29
  • found this question, looks like what you're trying to do. stackoverflow.com/questions/1545316/… Commented Feb 9, 2016 at 12:30

1 Answer 1

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()
};
Sign up to request clarification or add additional context in comments.

7 Comments

OK Jay, I'll try this
Hello Jay, Nice solution but this not worked for me. Is there any different way to implement this?
edited my answer, you need to make your data: line match your controller param names
I used data: JSON.stringify({usermaster: usermodel, citydata: citydatamodel}), , but it does not executed
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.