开发者

MVC 3 Validation htmlAttributes on hidden input

I've got some mvc3 client side validation that is acting strange.

In my controller I've got

ViewBag.Id = item.Id;
ViewBag.reqAction = item.RequestedAction;
return View("Decline");

In my view I've got

@Html.HiddenFor(model => model.Id, new { value = ViewBag.Id })
@Html.HiddenFor(model => model.RequestedAction, new { value = ViewBag.reqAction })

No matter what I do the value for RequestedAction comes up blank. I've even tried...

@Html.HiddenFor(model => model.RequestedAction, new { value = "test" })

The value for Id works perfectly, and the validation works on the other fields (I've omitted). I've traced the code and ViewBag.reqAction has the exact value I think it should have. My ViewModel looks like this...

    [Required]
    public int Id { get; set; }

  开发者_开发技巧  [Required]
    public string RequestedAction { get; set; }

    [Required]
    [DataType(DataType.MultilineText)]
    public string Explanation { get; set; }

Why can't I get any data into the value attribute for the RequestedAction hidden input?


I believe MVC is attempting to get the value from the model itself. When it merges the htmlAttributes it is overwriting the value you specify. The reason why Id works is MVC is probably getting the value from some other location (maybe ViewBag). Try setting the value on the model directly (or put it in modelstate)


It is my understanding that the client-side validation won't check the values of hidden fields (I had the same problem).

My work-around was to simply use input fields (using HTML.EditorFor) since I knew that worked fine on both client/server side. I then wrapped all the EditorFor's that are supposed to be hidden inside of a div with a class "HiddenValidator" and use jQuery to hide that class on document.ready.

Maybe not the prettiest solution but it gets the job done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜