Sealer_05
Sealer_05

Reputation: 5566

JsonResult controller parameter always null

I am using extremely similar code on another view and controller that is working perfectly but for some reason I cannot get this one to work. No matter what I do the controller parameters show undefined even though name and pass in the javascript are working correctly. Any help would be appreciated!

View:

@using (Html.BeginForm())
{
 <fieldset>
 <legend>User</legend>
       Username:
            @Html.TextBox("txtUsername")
       <br/>
       Password:
            @Html.TextBox("txtPassword")
       <br />
       <p>
            <input type="submit" id="btnLogin" value="Login" />
       </p>
 </fieldset>
 }       

 <script>

 $(function() {
      $("#btnLogin").click(login);
 });

     function login() {
         var name = $('#txtUsername').val();
         var pass = $('#txtPassword').val();

     $.post("/User/Login/" + name + "/" + pass, null, loginSuccess, "json");
}

function loginSuccess(result) {
    alert(result);
}

</script>


Controller:

public ActionResult Login()
{
    return View("Login");
}

[HttpPost]
public JsonResult Login(string name, string pass)
{
    string result = "test result";

    return Json(result);
}

Upvotes: 0

Views: 3122

Answers (6)

ken4z
ken4z

Reputation: 1390

You may be able to do it the way you have it, but I would need to see your routes as well. There is a better way to make this call though.

var data = {
    "name": $('#txtUsername').val(),
    "pass": $('#txtPassword').val()
};

$.post('@Url.Action("Login", "Home")', data, function(response) {
   //Do something with the response if you like
});

Upvotes: 2

YS.Tan
YS.Tan

Reputation: 551

all you need is:

View:

@using (Html.BeginForm())
{
 <fieldset>
 <legend>User</legend>
   Username:
        @Html.TextBox("txtUsername")
   <br/>
   Password:
        @Html.TextBox("txtPassword")
   <br />
   <p>
        <input type="button" id="btnLogin" value="Login" />
   </p>
 </fieldset>
 }      

Then the controller:

Controller:

public ActionResult Login()
{
    return View("Login");
}

[HttpPost]
public JsonResult Login(string name, string pass)
{
    string result = "test result";

    return Json(result);
}

The ajax part:

<script type="text/javascript">
$( "#btnLogin" ).click(function() {


$.ajax({
                url: "@Url.Action("YourControllerActionName", "YourControllerName")",
                type: 'POST',
                data: {
                    name: $('#txtUsername').val(),
                    pass: $('#txtPassword').val()
                },
                success: function(result) {
                      alert(result); 
                }
            });
});
<script>

Upvotes: 3

Rahul
Rahul

Reputation: 2307

You can Post it as ::

    $.ajax({
           type:'POST',
           url:"User/Login",
           data:{UserName:$("#UserName").val(),Password:$("#Password").val()},
           success:function(data){
               alert(data);
           }
    })

and On Server side you will get the Information like::

[HttpPost]
public JsonResult Login(string Username, string Password)
{
    string result = "test result";

    return Json(result);
}

Upvotes: 1

Rowan Freeman
Rowan Freeman

Reputation: 16358

I don't like string concatenation and hard-coded strings.

First, let's use an HTML helper to resolve an action's URL.

@Url.Action("Login", "User")

Second, let's pass the data as a javascript object.

$.post("@Url.Action("Login", "User")",
    {
        name: name,
        pass: pass
    }, loginSuccess, "application/json");

Upvotes: 2

tlt
tlt

Reputation: 15221

you are sending parameters as a part of the URL (thus, effectively, making it GET regardless of jquery $.post() ) and your controller strictly expects HttpPost (meaning, parameters in http request body, not in query string).

leaving aside that fact that having username/password in url is extremely bad practice.

try sending data as:

$.post('url/of/the/controller', {name: $('#txtUsername').val(), pass: $('#txtPassword').val()});

Upvotes: 2

edhedges
edhedges

Reputation: 2718

You are making the call your controller action method incorrectly. Try passing name and pass as data in the $.post call instead of appended on to the url.

It also may be cleaner to make your controller action method take a model of type LogIn. LogIn could have two properties (Name and Pass). That way when you send data in $.post you can send it like { name: 'someName', pass: 'somePass' }.

Upvotes: 1

Related Questions