我在视图上出现了客户端验证问题,该视图在Html.RenderAction的帮助下呈现下拉列表。
我有两个控制器。SpecieController、CatchController和我已经为我的视图创建了ViewModels。我想让它尽可能的干燥,而且在不久的将来,我很可能需要一种DropDownList。
当我创建一个捕获,我需要设置一个关系到一个物种,我这样做的id,我从物种的DropDownList获得。
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.DropDownList
public DropDownList(IEnumerable<SelectListItem> species) { this.Species = species; }
public IEnumerable<SelectListItem> Species { get; private set; }我对Catch.Create操作的视图使用ViewModels.Catch.Create作为模型。
但我觉得我在暗示中遗漏了什么。在我的头脑中,我想要的是将DropDownList中来自RenderAction的选定值连接到我的SpecieId上。
View.Catch.Create
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<BC.ProjectName.Web.ViewModels.CatchModels.Create>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<div class="row">
<div class="editor-label">
<%: Html.LabelFor(model => model.Weight) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Weight) %>
<%: Html.ValidationMessageFor(model => model.Weight) %>
</div>
</div>
<div class="row">
<div class="editor-label">
<%: Html.LabelFor(model => model.Length) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Length) %>
<%: Html.ValidationMessageFor(model => model.Length) %>
</div>
</div>
<div class="row">
<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>
</div>
<div class="clear"></div>
<input type="submit" value="Save" />
</fieldset>
<% } %>
</asp:Content>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);
// After save redirect
return Redirect("/");
}
// Invalid
return View();
}这个场景可以工作,但不像我想的那么顺利。
提前谢谢你花时间在这件事上。
发布于 2010-11-20 00:21:19
我不确定这是否有帮助,但我使用的是xVal而不是MVC2 2的客户端验证,在您所描述的场景中,它工作得很好。我有很多客户端验证的DropDownLists,我主要用RenderAction呈现它们。
https://stackoverflow.com/questions/2952876
复制相似问题