Skip to content Skip to sidebar Skip to footer

How To Post Data From Viewmodel Into A Controller Method?

I'm trying to post data from a JavaScript function into a controller method. It's working fine when I have a simple model, but it's not working when I try to post data when working

Solution 1:

UPD

0) please, fix your naming in ViewModel (LoginModAl => LoginModEl)

1) put this

public JsonResult Login([FromBody]ViewModel data)

please, check this one binding

2) you need to add id, because you got undefined fields, like this: enter image description here

<inputtype="text" name="username"id="username" >   
<inputtype="password" name="password"id="password">

3) then, you need add contentType and Json.stringify:

$.ajax({
        type: "POST",
        url: "Home/Login",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            "loginModel":{
                "Username": usr,
                "Password": pwd
            }

        }),

I create new app and its looks fine: client data: enter image description here

and dto in controller: enter image description here

i hope in this time it`ll be helpful

Solution 2:

When posting data into MVC, you'll need to match your properties with the parameters being posted.

In your javascript your are posting an object that looks like this:

{    
    "Username": usr,
    "Password": pwd
}

But your view model is expecting something like:

{
    "LoginModal": {
        "Username": usr,
        "Password": pwd
    }
}

One way to fix this is to modify the javascript:

functionpostIt() {
    var usr = $("#username").val();
    var pwd = $("#password").val();
    $.ajax({
        type: "POST",
        url: "Home/Login",
        data: {
            "LoginModal": {
                "Username": usr,
                "Password": pwd
            }
        },
        success: function(data) {
            if (data.result) {
                alert(data.message);
            } else {
                // unauthorizedalert(data.message);
            }
        }
    });
}

However, I would not recommend this. You are trying to do too much with the view model and should consider breaking these into separate ViewModels and Views

Post a Comment for "How To Post Data From Viewmodel Into A Controller Method?"