简体   繁体   English

MVC ajax post到控制器动作方法

[英]MVC ajax post to controller action method

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.我一直在看这里的问题: MVC ajax json post to controller action method但不幸的是它似乎并没有帮助我。 Mine is pretty much the exact same, except my method signature (but I've tried that and it still doesn't get hit).我的几乎完全相同,除了我的方法签名(但我已经尝试过了,它仍然没有被击中)。

jQuery 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.但是,无论我尝试什么,我的Controller不会被击中。 Through debugging, I know that it sends a request, it just gets a Not Found error each time.通过调试,我知道它发送了一个请求,但每次都会得到一个Not Found错误。

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.此外,toStringify() 在这里可能不是您想要的。 Just send the object itself.只需发送对象本身。

data: data,

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
}

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

I found this way of using ajax which helped me as it was better in use as not having complex json syntaxes我发现这种使用 ajax 的方式对我有帮助,因为它没有复杂的 json 语法,因此使用起来更好

//fifth
function GetAjaxDataPromise(url, postData) {
    debugger;
    var promise = $.post(url, postData, function (promise, status) {
    });
    return promise;
};
$(function () {
    $("#btnGet5").click(function () {
        debugger;
        var promises = GetAjaxDataPromise('@Url.Action("AjaxMethod", "Home")', { EmpId: $("#txtId").val(), EmpName: $("#txtName").val(), EmpSalary: $("#txtSalary").val() });
        promises.done(function (response) {
            debugger;
            alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
        });
    });
});

This method comes with jquery promise the best part was on controller we can received data by using separate parameters or just by using a model class.这个方法带有 jquery 承诺,最好的部分是在控制器上,我们可以通过使用单独的参数或仅使用模型类来接收数据。

[HttpPost]
    public JsonResult AjaxMethod(PersonModel personModel)
    {
        PersonModel person = new PersonModel
        {
            EmpId = personModel.EmpId,
            EmpName = personModel.EmpName,
            EmpSalary = personModel.EmpSalary
        };
        return Json(person);
    }

or或者

[HttpPost]
    public JsonResult AjaxMethod(string empId, string empName, string empSalary)
    {
        PersonModel person = new PersonModel
        {
            EmpId = empId,
            EmpName = empName,
            EmpSalary = empSalary
        };
        return Json(person);
    } 

It works for both of the cases.它适用于这两种情况。 SO you must try out this way.所以你必须尝试这种方式。 Got the reference fromUsing Ajax With Asp.Net MVCUsing Ajax With Asp.Net MVC获得参考

There are few more ways of using Ajax explained there other than this one which you must try.除了您必须尝试的这种方法之外,还有其他几种使用 Ajax 的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM