从asp.net mvc actionresult返回bool

时间:2010-03-03 20:55:19

标签: jquery asp.net-mvc

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

这是控制器方法的代码:

    [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
        }
    }

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

3 个答案:

答案 0 :(得分:76)

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

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

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

答案 1 :(得分:4)

恕我直言,您应该使用JsonResult代替ActionResult(代码可维护性)。

在Jquery方面处理响应:

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

希望有所帮助:)

答案 2 :(得分:2)

这个怎么样:

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

        return true;
    }
    catch
    {
        return false;
    }
}
相关问题