我只是想在MVC RC中进行一些简单的验证,并且收到错误。出于这个问题的目的,我没有使用UpdateModel 。
以下是表单中的代码:
<%= Html.TextBox("UserId")%>
<%= Html.ValidationMessage("UserId") %>
如果我在控制器中添加以下行,我将在TextBox上得到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 :(得分: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));
}
答案 1 :(得分:0)
您绝对不需要调用SetModelValue。
也许你只需要你的视图从你传入的模型中拉出文本框?
<%= Html.TextBox("UserId", Model.UserId)%>
我就是这样做的。
答案 2 :(得分: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);
}
}