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 
   });

  });     
});

EmptyResultActionメソッドから戻る理由がわかりません。実行しようとしているアクションのステータスを示す有効な応答を返す必要がある場合があります。

[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 に答える