2012-09-11 27 views
2

我使用MVC4來構建應用程序這是一個問題發生器允許用戶問一大堆的問題,並與真/假如果需要,他們或者設置不。創建動態控制與mvc4和應用驗證,只有一些領域

我現在正在爲用戶回答問題準備好問題。

我想啓用服務器端和客戶端驗證。

將所需字段應用於已設置爲必需的問題的最佳方法是什麼?

如果我有一個像

public class TestModel 
{ 
    public Guid Id { get; set; } 
    public string Question { get; set; } 
    public bool Required { get; set; } 
} 

public class TestViewModel 
{ 
    public string TestName { get; set; } 
    public List<TestModel> Tests { get; set; } 
} 

一個簡單的模型和視圖模型我不能只是添加[必需]屬性的問題性質

是否有可能申請驗證才qeustions哪裏Required屬性設置爲true?

回答

4

你可以很容易地做到這一點與MVC Foolproof的NuGet:

只需安裝它:

install-package foolproof 

現在你可以有以下型號:

public class TestModel 
{ 
    public Guid Id { get; set; } 
    public string Question { get; set; } 

    [RequiredIf("Required", true)] 
    public string Answer { get; set; } 
    public bool Required { get; set; } 
} 

public class TestViewModel 
{ 
    public string TestName { get; set; } 
    public List<TestModel> Tests { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new TestViewModel 
     { 
      TestName = "The test", 
      Tests = new[] 
      { 
       new TestModel { Id = Guid.NewGuid(), Question = "q1", Required = true }, 
       new TestModel { Id = Guid.NewGuid(), Question = "q2", Required = true }, 
       new TestModel { Id = Guid.NewGuid(), Question = "q3", Required = false }, 
       new TestModel { Id = Guid.NewGuid(), Question = "q4", Required = true }, 
      }.ToList() 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(TestViewModel model) 
    { 
     return View(model); 
    } 
} 

相應~/Views/Index.cshtml觀點:

@model TestViewModel 

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/mvcfoolproof.unobtrusive.min.js")" type="text/javascript"></script> 

<h2>@Html.DisplayFor(x => x.TestName)</h2> 

@using (Html.BeginForm()) 
{ 
    @Html.HiddenFor(x => x.TestName) 
    @Html.EditorFor(x => x.Tests) 
    <button type="submit">OK</button> 
} 

最後的TestModel自定義編輯器模板(~/Views/Home/EditorTemplates/TestModel.cshtml):

@model TestModel 

<div> 
    @Html.HiddenFor(x => x.Id) 
    @Html.HiddenFor(x => x.Required) 
    @Html.HiddenFor(x => x.Question) 
    @Html.LabelFor(x => x.Answer, Model.Question) 
    @Html.EditorFor(x => x.Answer) 
    @Html.ValidationMessageFor(x => x.Answer) 
</div> 
+0

哇!感謝Darin提供了這樣一個詳細的答案。我欣賞你所採取的時間。 –