MVC ajax发布到控制器动作方法

时间:2022-12-01 23:16:20

I've been looking at the question here: MVC ajax json post to controller action method but unfortunately it doesn't seem to be helping me. Mine is pretty much the exact same, except my method signature (but I've tried that and it still doesn't get hit).

我一直在看这里的问题:MVC ajax json发布到控制器动作方法但不幸的是它似乎没有帮助我。除了我的方法签名之外,我的情况几乎完全相同(但我已经尝试过,但它仍然没有被击中)。

jQuery

$('#loginBtn').click(function(e) {
    e.preventDefault();

    // TODO: Validate input

    var data = {
        username: $('#username').val().trim(),
        password: $('#password').val()
    };

    $.ajax({
        type: "POST",
        url: "http://localhost:50061/checkin/app/login",
        content: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(data),
        success: function(d) {
            if (d.success == true)
                window.location = "index.html";
            else {}
        },
        error: function (xhr, textStatus, errorThrown) {
            // TODO: Show error
        }
    });
});

Controller

[HttpPost]
[AllowAnonymous]
public JsonResult Login(string username, string password)
{
    string error = "";
    if (!WebSecurity.IsAccountLockedOut(username, 3, 60 * 60))
    {
        if (WebSecurity.Login(username, password))
            return Json("'Success':'true'");
        error = "The user name or password provided is incorrect.";
    }
    else
        error = "Too many failed login attempts. Please try again later.";

    return Json(String.Format("'Success':'false','Error':'{0}'", error));
}

However, no matter what I try, my Controller never gets hit. Through debugging, I know that it sends a request, it just gets a Not Found error each time.

但是,无论我尝试什么,我的控制器永远不会被击中。通过调试,我知道它发送了一个请求,每次都会收到Not Found错误。

4 个解决方案

#1


13  

Your Action is expecting string parameters, but you're sending a composite object.

您的Action需要字符串参数,但您正在发送复合对象。

You need to create an object that matches what you're sending.

您需要创建一个与您发送的内容相匹配的对象。

public class Data
{
    public string username { get;set; }
    public string password { get;set; }
}

public JsonResult Login(Data data)
{
}

EDIT

编辑

In addition, toStringify() is probably not what you want here. Just send the object itself.

另外,toStringify()可能不是你想要的。只需发送对象本身。

data: data,

#2


3  

It's due to you sending one object, and you're expecting two parameters.

这是由于您发送了一个对象,并且您期望有两个参数。

Try this and you'll see:

试试这个,你会看到:

public class UserDetails
{
   public string username { get; set; }
   public string password { get; set; }
}

public JsonResult Login(UserDetails data)
{
   string error = "";
   //the rest of your code
}

#3


3  

try this:

尝试这个:

/////// Controller post and get simple text value 
[HttpPost]
    public string Contact(string message)
    { 
        return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
    }

//// in the view add reference to the Javascript (jQuery) files

////在视图中添加对Javascript(jQuery)文件的引用

@section Scripts{

<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>  
}

/// then add the Post method as following:

///然后添加Post方法如下:

<script type="text/javascript"> 

/// post and get text value

$("#send").on("click", function () {    
$.post('', { message: $('#msg').val() })  

//// empty post('') means post to the default controller, 
///we are not pacifying different action or controller
/// however we can define a url as following:
/// var url = "@(Url.Action("GetDataAction", "GetDataController"))"

         .done(function (response) {
             $("#myform").html(response);
        })
        .error(function () { alert('Error') })
        .success(function () { alert('OK') })
        return false;
    }); 

Now let's say you want to do it using $.Ajax and JSON:

现在让我们假设您想使用$ .Ajax和JSON来实现它:

// Post JSON data  add using System.Net;
    [HttpPost]
    public JsonResult JsonFullName(string fname, string lastname)
    {
        var data = "{ \"fname\" : \"" + fname  + " \" , \"lastname\" : \"" + lastname + "\" }";
//// you have to add the JsonRequestBehavior.AllowGet 
 //// otherwise it will throw an exception on run-time.
        return Json(data, JsonRequestBehavior.AllowGet);  
    }

Then, inside your view: add the event click on a an input of type button, or even a from submit: Just make sure your JSON data is well formatted.

然后,在视图中:添加事件单击类型按钮的输入,甚至是来自提交:只需确保您的JSON数据格式正确。

  $("#jsonGetfullname").on("click", function () { 
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "@(Url.Action("JsonFullName", "Home"))",
            data: "{ \"fname\" : \"Mahmoud\" , \"lastname\" : \"Sayed\" }",
            dataType: "json",
            success: function (data) {
                var res = $.parseJSON(data);
                $("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
            }, 
            error: function (xhr, err) {
                alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
                alert("responseText: " + xhr.responseText);
            } 
        })
    });

cheers,

干杯,

Mahmoud Sayed

马哈茂德赛义德

#4


-3  

$('#loginBtn').click(function(e) {
    e.preventDefault(); /// it should not have this code or else it wont continue
    //....
});

#1


13  

Your Action is expecting string parameters, but you're sending a composite object.

您的Action需要字符串参数,但您正在发送复合对象。

You need to create an object that matches what you're sending.

您需要创建一个与您发送的内容相匹配的对象。

public class Data
{
    public string username { get;set; }
    public string password { get;set; }
}

public JsonResult Login(Data data)
{
}

EDIT

编辑

In addition, toStringify() is probably not what you want here. Just send the object itself.

另外,toStringify()可能不是你想要的。只需发送对象本身。

data: data,

#2


3  

It's due to you sending one object, and you're expecting two parameters.

这是由于您发送了一个对象,并且您期望有两个参数。

Try this and you'll see:

试试这个,你会看到:

public class UserDetails
{
   public string username { get; set; }
   public string password { get; set; }
}

public JsonResult Login(UserDetails data)
{
   string error = "";
   //the rest of your code
}

#3


3  

try this:

尝试这个:

/////// Controller post and get simple text value 
[HttpPost]
    public string Contact(string message)
    { 
        return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
    }

//// in the view add reference to the Javascript (jQuery) files

////在视图中添加对Javascript(jQuery)文件的引用

@section Scripts{

<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>  
}

/// then add the Post method as following:

///然后添加Post方法如下:

<script type="text/javascript"> 

/// post and get text value

$("#send").on("click", function () {    
$.post('', { message: $('#msg').val() })  

//// empty post('') means post to the default controller, 
///we are not pacifying different action or controller
/// however we can define a url as following:
/// var url = "@(Url.Action("GetDataAction", "GetDataController"))"

         .done(function (response) {
             $("#myform").html(response);
        })
        .error(function () { alert('Error') })
        .success(function () { alert('OK') })
        return false;
    }); 

Now let's say you want to do it using $.Ajax and JSON:

现在让我们假设您想使用$ .Ajax和JSON来实现它:

// Post JSON data  add using System.Net;
    [HttpPost]
    public JsonResult JsonFullName(string fname, string lastname)
    {
        var data = "{ \"fname\" : \"" + fname  + " \" , \"lastname\" : \"" + lastname + "\" }";
//// you have to add the JsonRequestBehavior.AllowGet 
 //// otherwise it will throw an exception on run-time.
        return Json(data, JsonRequestBehavior.AllowGet);  
    }

Then, inside your view: add the event click on a an input of type button, or even a from submit: Just make sure your JSON data is well formatted.

然后,在视图中:添加事件单击类型按钮的输入,甚至是来自提交:只需确保您的JSON数据格式正确。

  $("#jsonGetfullname").on("click", function () { 
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "@(Url.Action("JsonFullName", "Home"))",
            data: "{ \"fname\" : \"Mahmoud\" , \"lastname\" : \"Sayed\" }",
            dataType: "json",
            success: function (data) {
                var res = $.parseJSON(data);
                $("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
            }, 
            error: function (xhr, err) {
                alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
                alert("responseText: " + xhr.responseText);
            } 
        })
    });

cheers,

干杯,

Mahmoud Sayed

马哈茂德赛义德

#4


-3  

$('#loginBtn').click(function(e) {
    e.preventDefault(); /// it should not have this code or else it wont continue
    //....
});