return bool from asp.net mvc actionresult

Jqueryasp.net Mvc

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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 : )

Solution 3 - Jquery

How about this:

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

        return true;
    }
    catch
    {
        return false;
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShawn McleanView Question on Stackoverflow
Solution 1 - JqueryMattias JakobssonView Answer on Stackoverflow
Solution 2 - JquerySDReyesView Answer on Stackoverflow
Solution 3 - JqueryAgentFireView Answer on Stackoverflow