简体   繁体   中英

ASP.NET MVC 4 C# Failed Connected Ajax Post With Model

I'm making an AAX request using jQuery, post like this:

$("#frm").submit(function (e) {
    $.ajax({
        url: "/My/Controller/Action",
        type: "POST",
        data: $(this).serialize(),
        dataType: "json",
        success: function (status) {
            alert("Success");
        },
        error: function () {
            alert("Error");
        }
    });
    e.preventDefault();
});

and here my controller :

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult QuizCalculation()
{
    foreach (string keys in Response.Form.AllKeys)
    {
        var m = db.Quiz.Single(h => h.id == keys);
    }

    Request.AcceptTypes.Contains("application/json");
    return Json(new { status = true });
}

But it always returns an error :

Operator '==' cannot be applied to operands of type 'int' and 'string'

in part => h.id == keys

Please help me. Any idea on what is causing this?

You need to either convert id to a string, or keys to an int . Try this:

foreach (string keys in Response.Form.AllKeys)
{
    var m = db.Quiz.Single(h => h.id.ToString() == keys);
}

Or this:

foreach (string keys in Response.Form.AllKeys)
{
    var m = db.Quiz.Single(h => h.id == Int16.Parse(keys));
}

Also, you should look in to using ModelBinding to receive your parameters, instead of looping through the Form .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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