2012-06-29 65 views
1

我有一個html輸入文本字段和一個按鈕。通過AJAX發送並獲得MVC3控制器的價值

我想通過單擊該按鈕並從該HTML文本字段獲取用戶輸入值並希望將該值(通過AJAX)發送到MVC3控制器(就像ActionResult setValue()的參數一樣)?

我想知道的其他事情,我如何從MVC3控制器獲取返回值(即通過ActionResult getValue()返回)並將其設置爲HTML文本字段(通過AJAX)?

請幫助我一個很好的例子,請。併爲我的糟糕英語感到抱歉。 :)

回答

6

按鈕單擊事件

$(document).ready(function() 
{ 
    $('#ButtonName').click(function() 
    { 
     if ($('#YourHtmlTextBox').val() != '') 
     { 
      sendValueToController(); 
     } 
     return false; 
    }); 
}); 

你叫你的Ajax功能,像這樣:

function sendValueToController() 
{ 
    var yourValue = $('#YourHtmlTextBox').val(); 

    $.ajax({ 
     url: "/ControllerName/ActionName/", 
     data: { YourValue: yourValue }, 
     cache: false, 
     type: "GET", 
     timeout: 10000, 
     dataType: "json", 
     success: function (result) 
     { 
      if (result.Success) 
      { // this sets the value from the response 
       $('#SomeOtherHtmlTextBox').val(result.Result); 
      } else 
      { 
       $('#SomeOtherHtmlTextBox').val("Failed"); 
      } 
     } 
    }); 
} 

這是被稱爲

public JsonResult ActionName(string YourValue) 
{ 
    ... 
    return Json(new { Success = true, Result = "Some Value" }, JsonRequestBehavior.AllowGet); 
} 
+0

謝謝你這麼多的操作: ) – zxprince

+0

沒問題,樂於幫忙! –

+0

你的例子你發送一個字符串到該動作,我如何發送一個數組,並通過索引獲取值? – zxprince

相關問題