Asp.net-Mvc

asp.net mvc 3 - ajax 表單送出和驗證

  • March 4, 2011

很抱歉,如果這已經被問過了,但我一直在尋找一段時間,但我發現的都是相當老的文章(mvc1,mvc2)。我有一個表格,我想通過 Ajax 送出。

看起來可行,但不包括伺服器端驗證。

  1. 我不確定是否應該使用AjaxHelper.BeginForm或使用原始 jquery 呼叫($.ajax)?這裡推薦的方法是什麼?

2)如何處理客戶端和伺服器端驗證?我希望 mvc 框架提供一個內置機制來處理這個問題?有一些驗證我只在伺服器端進行。在這裡使用ValidationSummary仍然有效嗎?

我正在使用帶有不顯眼的 javascript 驗證的 asp.net mvc3/razor。

謝謝!

編輯:(根據下面的 Bobby B 的要求)。 這是在提出問題幾個月後添加的,因為使用者想知道如何使用 AjaxHelper

這是我使用的 javascript 程式碼:

<script type="text/javascript">

function ajaxValidate() {
 return $('form').validate().form();
}

function getGbPostSuccess(ajaxContext){
 // .... it is not necessary to do anything here.
}
function showFaliure(ajaxContext){
  // handle failure
}

HTML 片段:

@using (Ajax.BeginForm("Index", "Home", new AjaxOptions
                       {
                           UpdateTargetId = "form1",
                           InsertionMode = InsertionMode.Replace,
                           OnBegin = "ajaxValidate",
                           OnSuccess = "getGbPostSuccess",
                           OnFailure = "showFaliure"
                       }))
{

為此,我已經使用了一段時間的 malsup 的 jQuery 表單外掛。老實說,我對 AjaxHelper 並不熟悉,但看起來它確實可以滿足您的需求。就客戶端和伺服器端驗證而言,只要您使用模型綁定和 System.DataAnnotations 命名空間中的屬性,這一切都應該自動發生。

public class MyModel
{
   [Required(ErrorMessage = "Please enter your name")]
   public String Name { get; set; }

   [Required(ErrorMessage = "Please enter your email")]
   public String Email { get; set; }

   [Required(ErrorMessage = "Please enter a rating")]
   [Range(1, 5, ErrorMessage = "The rating must be between 1 and 5")]
   public Int32 Rating { get; set; }
}

[HttpPost]
public ActionResult Index(MyModel myModel)
{
  if(ModelState.IsValid)
  {
      // good to go, put it in the DB or whatever you need to do
  }
  else 
  {
      return View(model); // return the user back to the page, ModelState errors can be viewed using Html.ValidationSummary() or individual Html.ValidationMessageFor() calls
  }
}

如果您正在執行自己的自定義伺服器端驗證,則可以通過創建實現 ValidationAttribute 的屬性來創建自己的自定義驗證屬性,或者通過呼叫 ModelState.Errors.Add() (或那裡的其他內容,我手邊沒有參考資料)

對於客戶端,MVC 將根據模型上的 DataAnnotations 屬性為您生成客戶端驗證。

引用自:https://stackoverflow.com/questions/5200098