我在用Html.RenderAction幫助呈現下拉列表的View上遇到客戶端驗證問題。MVC2客戶端驗證與RenderAction視圖中的註釋
我有兩個控制器。 SpecieController和CatchController,我爲我的視圖創建了ViewModels。 我想盡可能保持乾燥,我很可能需要在不久的將來在其他地方的所有物種的DropDownList。
當我創建一個Catch時,我需要將一個關係設置爲一個物種,我使用從物種的DropDownList中獲得的一個ID來執行此操作。
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作爲模型。
但感覺我在實現中缺少了一些東西。我想要的是將來自RenderAction的DropDownList中的選定值連接到我的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();
}
這個場景的作品,但並不順利,因爲我想要的。
- ClientSide驗證不適用於SpecieId(我重構後),我明白爲什麼,但不知道如何才能ix它。
- 我能「膠水」將DropDownList的SelectedValue到myCatch所以我並不需要從請求[「種」]獲得價值
預先感謝你的時間在這。
請問您可以查看您的視圖和創建操作的整個代碼嗎? 客戶端驗證通常與以下html助手一起應用:'Html.EnableClientSideValidation()' – 2010-06-01 23:03:05
整個代碼,粘貼。 ClientValidation適用於其他字段,長度和重量。在重構RenderAction之前,它也用於下拉菜單。 Species集合然後被放置在Catch.Create對象的旁邊,長度,重量和SpecieId道具。 – Olle 2010-06-02 09:24:16