2010-09-06 74 views
0

我正在使用ASP.NET MVC 2.我有一個模式對話框(通過jQuery UI完成),它包含兩個文本框和一個按鈕。所有的控件都在一個表單中。使用jquery調用動作ajax

我想在用戶單擊按鈕時調用一個控制器操作,對兩個文本框中包含的傳遞數據執行一些操作,然後向用戶返回一個整數值和一個字符串消息。

任何人都可以提供一個用jQuery做這個的例子嗎?

非常感謝!

回答

3

假設你有以下形式:

<form id="ajax-form"> 
    <fieldset> 
     <input type="text" id="firstname" name="firstname" /> 
     <input type="text" id="lastname" name="lastname" /> 
     <input type="submit" value="send" /> 
    </fieldset> 
</form> 

使用jQuery

$(document).ready(function(){ 
$("#ajax-form").submit(function(){ 

    $.ajax({ 
      type: "POST", 
      url: "Person/Add", 
      data: $("#ajax-form").serialize(), 
      success: function (response) { 
       // whatever you want to happen on success 
      }, 
      error: function (response) { 
        alert('There was an error.'); 
       } 
     }); 

}); 

});

訪問操作方法中的數據。

public ActionResult Add(FormCollection form) 
{ 
    string firstname = form["firstname"]; 
    string firstname = form["lastname"]; 
    // do whatever you want here 
    // then return something to the view 
    return Json(/*some object*/); 
} 

另一種方法是使用微軟的Ajax

<% using (Ajax.BeginForm("Add", "Person", 
      new AjaxOptions() { 
           UpdateTargetId = "formDiv", 
           InsertionMode = InsertionMode.Replace, 
           HttpMethod = "Post" })) {%> 

     <fieldset> 

      // Form Elements Here.    

     </fieldset> 

<% } %> 

UpdateTargetId是HTML元素的ID爲目標。 的InsertionMode選項有三個值ReplaceInsertAfterInsertBefore

希望那是有益的

更新:你不必在你的操作方法返回一個JSON結果,你可以簡單地返回一個局部視圖或任何HTML代碼作爲響應對象,然後使用jQuery插入它。

+0

太棒了!非常感謝你!!! – Lorenzo 2010-09-06 17:55:34

+0

很高興我可以幫助:) – 2010-09-06 18:14:50

1

你可以看看documentation關於如何實現一個包含表單域的對話框。當點擊confirm按鈕時,您只需發送一個AJAX請求即可。

buttons: { 
    Confirm: function() { 
     // read the value in the textbox 
     var name = $('#name').val(); 

     // send an AJAX request to an action that will return JSON: 
     $.getJSON('/home/foo', { name: name }, function(result) { 
      // read the returned value 
      alert(result.Value); 
     }); 
    }, 
    Cancel: function() { 
     $(this).dialog('close'); 
    } 
} 

而且你的控制器動作:

public ActionResult Foo(string name) 
{ 
    return Json(new { Value = '123' }, JsonRequestBehavior.AllowGet); 
} 
+0

非常感謝您的參考和答案! – Lorenzo 2010-09-06 17:56:02