Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return bool from asp.net mvc actionresult

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?

like image 655
Shawn Mclean Avatar asked Mar 03 '10 20:03

Shawn Mclean


People also ask

What can I return from ActionResult in MVC?

ActionResult is a return type of a controller method in ASP.NET MVC. It help us to return models to views, other return value, and also redirect to another controller's action method. There are many derived ActionResult types in MVC that we use to return the result of a controller method to the view.

What does ActionResult return?

An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result.

Can I return ActionResult Instead of view results?

When you set Action's return type ActionResult , you can return any subtype of it e.g Json,PartialView,View,RedirectToAction.


2 Answers

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);     } } 
like image 80
Mattias Jakobsson Avatar answered Sep 27 '22 21:09

Mattias Jakobsson


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

like image 23
SDReyes Avatar answered Sep 27 '22 21:09

SDReyes