views:

158

answers:

2

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:

    [AcceptVerbs(HttpVerbs.Post)]
    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?

+8  A: 

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

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SetSchedule(FormCollection collection)
{
    try
    {
        // TODO: Add update logic here

        return Json(true);
    }
    catch
    {
        return Json(false);
    }
}
Mattias Jakobsson
+1, *files that in his memory for future use*
Alastair Pitts
+1  A: 

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

SDReyes
How does using a Json result instead of an ActionResult make the code more maintainable? AFAIK the type of result you use will only affect the type of the output the browser is expecting.
JoseMarmolejos
@JoseMarmolejos Hi Jose, I recommend you to return the most derived type you can in your methods, because it lets you to use the derived methods and properties of the return type without a checked down cast when required. same applies for events.By the other side due to the covariance rule, both options are the same for delegates use ; ) +1
SDReyes