簡體   English   中英

如何從MVC3中的javascript調用Controller方法?

[英]How to call a Controller method from javascript in MVC3?

我使用MVC3架構,c#.net。 當焦點更改為下一個字段即密碼字段時,我需要立即將文本框內容(用戶ID)與數據庫進行比較。 所以我想在用戶ID字段中使用onblur事件,然后調用Controller方法。 誰能告訴我如何處理這個問題? 作為一個新手,代碼片段受到高度贊賞。

提前致謝,

普拉香特

這是一個例子。 控制器方法的示例

[HttpPost] // can be HttpGet
public ActionResult Test(string id)
{
     bool isValid = yourcheckmethod(); //.. check
     var obj = new {
          valid = isValid
     };
     return Json(obj);
}

這將是你的javascript函數。

function checkValidId(checkId)
{
    $.ajax({
         url: 'controllerName/Test',
         type: 'POST',
         contentType: 'application/json;',
         data: JSON.stringify({ id: checkId }),
         success: function (valid)
         {
              if(valid) { 
                  //show that id is valid 
              } else { 
                  //show that id is not valid 
              }
         }
    });
}

請參閱JQuery.get()System.Web.Mvc.JsonResult

例如:

<script type="text/javascript">
    $('#userID').blur(function()
    {
        $.get('/Home/ValidateUserID/' + $(this).val(), {}, 
            function(data, status)
            {
                if( !data.success ) {
                    alert('User ID is invalid!');
                }
            });
    });
</script>

您需要一個操作來捕獲GET請求:

public class HomeController
{
    [HttpGet]
    public ActionResult ValidateUserID(string id)
    {
        bool superficialCheck = true;

        return Json(new { success = superficialCheck },
            JsonRequestBehavior.AllowGet);
    }
}

幾點,沒有特別的順序:

  • 請注意, .get的第一個參數是控制器操作的匹配URL?
  • #userID html字段的值附加到URL的末尾,允許MVC將數據綁定到操作參數ValidateUserID(string id)
  • Controller.Json方法將.NET對象格式化為JavaScript對象。 JQuery將格式化的對象作為回調函數中的data接收。
  • JsonRequestBehavior.AllowGet告訴MVC可以從.GET將數據傳回瀏覽器。

這聽起來像服務器端驗證,因此您可以使用客戶端驗證功能。

http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx

一般來說,這可以通過使用ajax調用來完成(不確定你是否使用jQuery,但如果沒有,並且沒有特殊限制,將鼓勵使用它):

http://api.jquery.com/jQuery.ajax/

在客戶端:

$.ajax({
            url: '@Url.Action("ActionName", "ControllerName")',
            type: "POST",
            async: true,
            dataType: "json",
            data: $('#form').serialize(),                    
            success: function (data) {
               // process result
            },
            error: function (request, status, error) {
               // process error message
            }
        });

在服務器端:

[HttpPost]
public virtual ActionResult ActionName() 
{
     return Json("value")
}

但一般來說,你應該從ASP.NET MVC 3 Ajax google,在網絡上有很多相關內容,你可能已經找到了你需要的東西。

您可以在控制器上使用RemoteValidation屬性和服務器端操作,通過MVC Unobstrusive javascript為您完成所有操作,而不需要為它編寫單行JS / Jquery。

這是你能做的:

假設您有一個名為AccountController控制器和一個名為CheckPassword ,它接受參數string password ,您可以將它放在您的視圖中:

$('#texboxId').blur(function() {
    $.ajax({
        url: '/Account/CheckPassword',
        data: { password: $('#texboxId').val() },
        success: function(data) {
            // put result of action into element with class "result"
            $('.result').html(data);
        },
        error: function(){
            alert('Error');
        }
    });
});

您的控制器操作大致如下所示:

public class AccountController : Controller
{
    public ActionResult CheckPassword(string password)
    {
        bool passwordIsCorrect = //do your checking;
        string returnString = "whatever message you want to send back";
        return Content(returnString);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM