0

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);
}
Sealer_05
  • 5,346
  • 8
  • 35
  • 53

6 Answers6

3

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>
YS.Tan
  • 511
  • 3
  • 6
  • 1
    This is not true if the OP really needs things done asynchronously and without a page reload. You're better off asking the OP (in a comment) why a particular approach is being used. With this approach the callback function `loginSuccess` will never be called. – Rowan Freeman Mar 12 '14 at 03:04
  • yea, probably I should add another ajax method. Editted answer. – YS.Tan Mar 12 '14 at 03:47
  • Using your exact ajax code I still get null. I obviously added the controller names etc. without the ajax it works but yes i would like it to be a ajax/json call. Im completely baffled – Sealer_05 Mar 12 '14 at 03:59
  • 1
    try change the button input type to **type="button"** – YS.Tan Mar 12 '14 at 04:50
  • That was it! Thank You. Please edit your answer to include and I will mark yours – Sealer_05 Mar 12 '14 at 05:39
2

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
});
ken4z
  • 1,340
  • 1
  • 11
  • 18
2

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");
Rowan Freeman
  • 15,724
  • 11
  • 69
  • 100
  • Looks good but I am getting a syntax error on this comma "User"), – Sealer_05 Mar 12 '14 at 02:54
  • 1
    It would just be the HTML parser complaining because, according to it, there is nothing in between the `(` and the `,` since it ignores the Razor syntax. It's pretty standard. You can ignore it or simply change it to `$.post("@Url.Action("Login", "User")",`. – Rowan Freeman Mar 12 '14 at 03:01
  • Gotcha, still getting null on the parameters in the json result. – Sealer_05 Mar 12 '14 at 03:09
  • No go... $(function() { $("#btnLogin").click(login); }); function login() { var name = $('#txtUsername').val(); var pass = $('#txtPassword').val(); $.post(@Url.Action("Login", "User"), { name: name, pass: pass }, loginSuccess, "application/json"); } function loginSuccess() { }; – Sealer_05 Mar 12 '14 at 03:22
  • No matter what I do username and password are still null – Sealer_05 Mar 12 '14 at 03:46
  • Make sure you add the quotes around Url.Action (updated my sample). Also, are you clicking the login button (and not pressing the enter key)? – Rowan Freeman Mar 12 '14 at 04:55
  • I'm guessing it was the quotes in front of "@Url that i was missing. Thanks for your help – Sealer_05 Mar 12 '14 at 05:39
2

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()});

dee zg
  • 13,793
  • 10
  • 42
  • 82
1

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' }.

edhedges
  • 2,722
  • 2
  • 28
  • 61
  • "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." Thank you! Can you show an example? – Sealer_05 Mar 12 '14 at 02:34
  • 1
    @osiris355 what? Edit: Okay look at this: http://stackoverflow.com/a/19663938/1165441 So your post would be `$.post("/User/Login/", { name: "someName", pass: "somePass" } );` – edhedges Mar 12 '14 at 02:34
  • I am new to mvc and json. Can you show how I would pass the data? I have only done it in the url which was working in my other views for some reason – Sealer_05 Mar 12 '14 at 02:36
  • @osiris355 I edited my comment. POST requests work different than GET in that you send data directly after the HTTP headers that your browser sends to the server. More on this here: http://stackoverflow.com/a/5876931/1165441 – edhedges Mar 12 '14 at 02:38
  • Still getting null in controller $(function() { $("#btnLogin").click(login); }); function login() { var name = $('#txtUsername').val(); var pass = $('#txtPassword').val(); $.post(@Url.Action("Login", "User"), { name: name, pass: pass }, loginSuccess, "application/json"); } function loginSuccess() { }; – Sealer_05 Mar 12 '14 at 03:23
  • Please don't mix Razor and JavaScript. Take a look at the links in previous comments. There are other questions similar to this. – edhedges Mar 12 '14 at 03:29
  • I did and no matter what I do it is always null. I think something else is going on – Sealer_05 Mar 12 '14 at 03:46
1

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);
}
Rahul
  • 2,309
  • 6
  • 33
  • 60