1

我的行动中有以下内容

[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?我只需要做一些事情,而不是离开现有的页面。

谢谢你。

4

1 回答 1

4

因为你的代码是这样的。当您单击按钮时,您正在调用DoSomethingjavascript 函数并在其中提交表单。所以和普通的表单提交一样(点击提交按钮提交)。这就是它重定向的原因(实际上是发布到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 
   });

  });     
});

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

[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);      
}
于 2012-07-20T20:57:01.097 回答