return bool from asp.net mvc actionresult

假如想象 提交于 2021-02-17 09:16:28

问题


I submitted a form via jquery, but I need the ActionResult to return true or 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?


回答1:


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

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

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



回答2:


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

To handle the response in Jquery side:

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

Hope it helps : )




回答3:


How about this:

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

        return true;
    }
    catch
    {
        return false;
    }
}


来源:https://stackoverflow.com/questions/2374879/return-bool-from-asp-net-mvc-actionresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!