jQuery 从 asp.net mvc actionresult 返回 bool

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2374879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:21:28  来源:igfitidea点击:

return bool from asp.net mvc actionresult

jqueryasp.net-mvc

提问by Shawn Mclean

I submitted a form via jquery, but I need the ActionResultto return true or false.

我通过 jquery 提交了一个表单,但我需要ActionResult来返回 true 或 false。

this is the code which for the controller method:

这是控制器方法的代码:

    [HttpPost]
    public ActionResult SetSchedule(FormCollection collection)
    {
        try
        {
            // TODO: Add update logic here

            return true; //cannot convert bool to actionresult
        }
        catch
        {
            return false; //cannot convert bool to actionresult
        }
    }

How would I design my JQuery call to pass that form data and also check if the return value is true or false. How do I edit the code above to return true or false?

我将如何设计我的 JQuery 调用以传递该表单数据并检查返回值是真还是假。如何编辑上面的代码以返回 true 或 false?

回答by Mattias Jakobsson

You could return a json result in form of a bool or with a bool property. Something like this:

您可以以 bool 或 bool 属性的形式返回 json 结果。像这样的东西:

[HttpPost]
public ActionResult SetSchedule(FormCollection collection)
{
    try
    {
        // TODO: Add update logic here

        return Json(true);
    }
    catch
    {
        return Json(false);
    }
}

回答by SDReyes

IMHO you should use JsonResultinstead of ActionResult(for code maintainability).

恕我直言,您应该使用JsonResult而不是ActionResult(为了代码可维护性)。

To handle the response in Jquery side:

要处理 Jquery 端的响应:

$.getJSON(
 '/MyDear/Action',
 { 
   MyFormParam: $('MyParamSelector').val(),
   AnotherFormParam: $('AnotherParamSelector').val(),
 },
 function(data) {
   if (data) {
     // Do this please...
   }
 });

Hope it helps : )

希望能帮助到你 : )

回答by AgentFire

How about this:

这个怎么样:

[HttpPost]
public bool SetSchedule(FormCollection collection)
{
    try
    {
        // TODO: Add update logic here

        return true;
    }
    catch
    {
        return false;
    }
}