ASP.net MVC控制器动作 - 如何防止重定向

时间:2012-07-20 20:48:46

标签: asp.net-mvc-3 jquery

我的行动

中有以下内容
[AjaxException] 
public ActionResult DoSomething(sring someParam1, string someParam2) {

    //do whatever you need to do here, db etc
    return new EmptyResult();
}

在我的HTML中

<form id="search-frm" name="search-frm" action="@Url.Action("DoSomething", "MyActions")" method="post" >

    <input type="button" id="search-btn" value="search" class="btn" onclick="DoSomething();return false;" />
    <input type="text" name="param1" id="param1" />
    <input type="text" name="param2" id="param2" />
</form>

在我的JS中

function DoSomething() {  
   $("#search-frm").submit();
   return false;
}

当我点击按钮时,控制器操作DoSomething完成后,我被重定向到MyActions/DoSomething。有没有办法不使用jquery $.ajax?我只需要做一些事情而不是离开现有页面。

谢谢。

1 个答案:

答案 0 :(得分:3)

因为你的代码是这样的。当您单击按钮时,您正在调用DoSomething javascript函数,并且您正在提交表单。所以它与普通表单提交相同(点击提交按钮提交)。这就是它重定向的原因(实际上是发布到DoSomething动作。

如果您不想离开当前页面,可以使用ajax进行发布并获得结果并保持在同一页面中。所以我会像你这样更改代码

1)从HTML标记中删除OnClick事件绑定

2)添加此javascript处理表单提交

$(function(){
  $("#search-frm").submit(e){

   e.preventDefault();  // prevent the default form posting. Let's stay here
   $.post("@Url.Action("DoSomething","MyActions")",$("#search-frm").serialize(), function(data){
          //do something with the response data 
   });

  });     
});

不确定为什么从Action方法返回EmptyResult。您可能需要返回一些有效的响应,指示您尝试执行的操作的状态。

[HttpPost]
public ActionResult DoSomething(string param1,string param2)
{
  //do something 
   return Json(new 
             { Status= true,
               Message="Succesfully saved"
             });      
}

您可以保留通用ViewModel来返回此类结果并使用它,而不是像上面那样动态输入。

public class OperationStatus
{
  public bool Status  { set;get;}
  public string Message { set;get;}
}

并在您的操作方法中

[HttpPost]
public ActionResult DoSomething(string param1,string param2)
{
  //do something 
  var res=new OperationStatus();
  res.Status=true;
  res.Message="Successfully Added";
   return Json(res);      
}
相关问题