MVC2 Client validation with Annotations in View with RenderAction
Posted
by Olle
on Stack Overflow
See other posts from Stack Overflow
or by Olle
Published on 2010-06-01T19:58:13Z
Indexed on
2010/06/01
20:03 UTC
Read the original article
Hit count: 784
I'm having problem with client side validation on a View that renders a dropdownlist with help of a Html.RenderAction.
I have two controllers. SpecieController and CatchController and I've created ViewModels for my views. I want to keep it as DRY as possible and I will most probably need a DropDownList for all Specie elsewhere in the near future.
When I create a Catch i need to set a relationship to one specie, I do this with an id that I get from the DropDownList of Species.
ViewModels.Catch.Create
[Required]
public int Length { get; set; }
[Required]
public int Weight { get; set; }
[Required]
[Range(1, int.MaxValue)]
public int SpecieId { get; set; }
ViewModels.Specie.List
public DropDownList(IEnumerable<SelectListItem> species) { this.Species = species; }
public IEnumerable<SelectListItem> Species { get; private set; }
My View for the Catch.Create action uses the ViewModels.Catch.Create as a model.
But it feels that I'm missing something in the implemetation. What I want in my head is to connect the selected value in the DropDownList that comes from the RenderAction to my SpecieId.
View.Catch.Create
<div class="editor-label">
<%: Html.LabelFor(model => model.SpecieId) %>
</div>
<div class="editor-field">
<%-- Before DRY refactoring, works like I want but not DRY
<%: Html.DropDownListFor(model => model.SpecieId, Model.Species) %>
--%>
<% Html.RenderAction("DropDownList", "Specie"); %>
<%: Html.ValidationMessageFor(model => model.SpecieId) %>
</div>
CatchController.Create
[HttpPost]
public ActionResult Create(ViewModels.CatchModels.Create myCatch)
{
if (ModelState.IsValid)
{
// Can we make this StronglyTyped?
int specieId = int.Parse(Request["Species"]);
// Save to db
Catch newCatch = new Catch();
newCatch.Length = myCatch.Length;
newCatch.Weight = myCatch.Weight;
newCatch.Specie = SpecieService.GetById(specieId);
newCatch.User = UserService.GetUserByUsername(User.Identity.Name);
CatchService.Save(newCatch);
}
This scenario works but not as smooth as i want.
- ClientSide validation does not work for SpecieId (after i refactored), I see why but don't know how I can ix it.
- Can I "glue" the DropDownList SelectedValue into myCatch so I don't need to get the value from Request["Species"]
Thanks in advance for taking your time on this.
© Stack Overflow or respective owner