2009-02-17 45 views
4

我只是想在MVC RC中做一些簡單的驗證,並得到一個錯誤。爲了這個問題的目的,我是不使用UpdateModelMVC RC驗證:這樣對嗎?

這是形式的代碼:

<%= Html.TextBox("UserId")%> 
<%= Html.ValidationMessage("UserId") %> 

如果我在控制器中添加以下行,我會在文本框一個NullReferenceException:

ModelState.AddModelError("UserId", "*"); 

因此,要解決這個問題,我還添加了以下行:

ModelState.SetModelValue("UserId", ValueProvider["UserId"]); 

爲什麼我必須重新綁定值? 我只需要添加錯誤就可以做到這一點,但似乎我不應該這樣做。我覺得我正在做一些不正確的事情,或者只是對綁定不夠熟悉。

它看起來像我不是唯一一個見過這個。根據請求,以下是控制器代碼:

[AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Create(FormCollection collection) 
    { 
     AppUser newUser = new AppUser(); 

     try 
     { 
      newUser.UserId = collection["UserId"]; 

      AppUserDAL.AddUser(newUser); 

      return RedirectToAction("Index"); 
     } 
     catch (Exception ex) 
     { 
      ViewData["ReturnMessage"] = ex.Message; 

      ModelState.AddModelError("UserId", "*"); 
      ModelState.SetModelValue("UserId", ValueProvider["UserId"]); 


      return View(newUser); 
     } 
+0

I也注意到了這一點,我把它寫成了我做錯了的東西,並繼續進行其他工作。 – 2009-02-17 23:33:17

+0

請問您可以添加頁面的完整代碼和控制器的方法? – zihotki 2009-02-18 06:05:59

回答

4

調用此擴展方法:

 public static void AddModelError (this ModelStateDictionary modelState, string key, string errorMessage, string attemptedValue) { 
     modelState.AddModelError (key, errorMessage); 
     modelState.SetModelValue (key, new ValueProviderResult (attemptedValue, attemptedValue, null)); 
    } 

來源:Issues with AddModelError()/SetModelValue with MVC RC1

0

您絕對不需要調用SetModelValue。

也許你只是需要你的視圖從你傳入的模型中拉出文本框?

<%= Html.TextBox("UserId", Model.UserId)%> 

這就是我如何做到的。

+0

我試過這個,它似乎也沒有工作。奇怪的是,當我將鼠標放在View中的代碼行中時,Model對象不爲空,我可以看到所有的值。 – 2009-03-05 23:52:51

0

你可以試試這個擴展與lambda表達式設置模型值:

/// <summary> 
    /// Sets model value. 
    /// </summary> 
    /// <typeparam name="TViewModel">The type of the view model.</typeparam> 
    /// <typeparam name="TProperty">The type of the property</typeparam> 
    /// <param name="me">Me.</param> 
    /// <param name="lambdaExpression">The lambda expression.</param> 
    ///<param name="value">New Value</param> 
    public static void SetModelValue<TViewModel, TProperty>(
     this ModelStateDictionary me, 
     Expression<Func<TViewModel, TProperty>> lambdaExpression, 
     object value) 
    { 

     string key = WebControlsExtensions.GetIdFor<TViewModel, TProperty>(lambdaExpression, "."); 

     if (!string.IsNullOrWhiteSpace(key)) 
     { 
      me.SetModelValue(key, new ValueProviderResult(value, String.Empty, System.Globalization.CultureInfo.InvariantCulture)); 
     } 
    } 

要獲得ID:

public static class WebControlsExtensions 
{ 

    /// <summary> 
    /// Devuelve el Id correspondiente a la expresión lambda pasada por parámetro reemplazando los caracteres inválidos por la cadena pasada por parámetro 
    /// </summary> 
    /// <typeparam name="TViewModel">El tipo del modelo</typeparam> 
    /// <typeparam name="TProperty">El tipo de la propiedad</typeparam> 
    /// <param name="expression">Expresión lambda</param> 
    /// <param name="invalidCharReplacement">Cadena de texto que reemplaza a los carácteres inválido</param> 
    /// <remarks> 
    /// Valid characters consist of letters, numbers, and the hyphen ("-"), underscore ("_"), and colon (":") characters. 
    /// All other characters are considered invalid. Each invalid character in originalId is replaced with the character specified in the HtmlHelper.IdAttributeDotReplacement property. 
    /// </remarks> 
    /// <returns> Devuelve el Id correspondiente a la expresión lambda</returns> 
    public static string GetIdFor<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression, string invalidCharReplacement) 
    { 
     return TagBuilder.CreateSanitizedId(ExpressionHelper.GetExpressionText(expression), invalidCharReplacement); 
    } 

}