2011-07-26 16 views
0

私は、必要なフィールドが異なる以外は同じ2つのフォームがある問題があります。たとえば、フォームに同じフィールドがあるとします:X、Y、およびZフォーム#1ではXは必須ですが、フォーム#2ではYが必要です。ASP.NET MVC多態性と強く型付けされたビューMVC

私はForm1とForm2という2つのビューモデルを同じプロパティで作成しましたが、異なるプロパティでRequired属性を使用しました。その後、IFormというインターフェースを作成し、両方のモデルを実装し、IFormに強く型付けされたViewを構築しました。

解決策の問題は、ビューに渡されるオブジェクトの動的タイプ(Form1またはForm2)ではなく、ASP.NET MVC 3がIFormで属性を読み取るため、クライアント側には取得されません私が欲しいJavaScriptのフィールドの検証。

強く型付けされたビューを各ビューモデルに作成する以外の方法があるのだろうかと思います。

答えて

2

私はあなたが(と思う)で説明するものと一緒にサンプルを入れていると私はそれが仕事を得ることができるよ:

@model Test.Controllers.IFoo 

<h2>Test</h2> 

<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> 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <legend>IFoo</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Name) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Name) 
      @Html.ValidationMessageFor(model => model.Name) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Description) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Description) 
      @Html.ValidationMessageFor(model => model.Description) 
     </div> 

     <p> 
      <input type="submit" value="Save" /> 
     </p> 
    </fieldset> 
} 

public class TestController : Controller 
{ 
    public ActionResult Foo() 
    { 
     return View("IFoo"); 
    } 

    [HttpPost] 
    public ActionResult Foo(Foo foo) 
    { 
     if (!ModelState.IsValid) 
      return View("IFoo", foo); 

     return RedirectToAction("Foo"); 
    } 

    public ActionResult Bar() 
    { 
     return View("IFoo"); 
    } 

    [HttpPost] 
    public ActionResult Bar(Bar bar) 
    { 
     if (!ModelState.IsValid) 
      return View("IFoo", bar); 

     return RedirectToAction("Bar"); 
    } 
} 

// The Interface - the Required attributes are not 
// on the interface, just the concrete classes 
public interface IFoo 
{ 
    string Name { get; set; } 
    string Description { get; set; } 
} 

// Concrete Class 1 - Name is required 
public class Foo : IFoo 
{ 
    [Required(ErrorMessage="Name is required.")] 
    public string Name { get; set; } 

    public string Description { get; set; } 
} 

// Concrete Class 2 - Description is required 
public class Bar : IFoo 
{ 
    public string Name { get; set; } 

    [Required(ErrorMessage = "Description is required.")] 
    public string Description { get; set; } 
} 

が、私はその後、強く型付けされたビューを定義しました

/test/fooを参照して保存を押すと、名前に検証エラーが表示されます。

私が/ test/barを参照して保存を押すと、説明の検証エラーが表示されます。

+0

あなたは正しいです。検証はサーバー側で行われます。しかし、jQueryクライアント側の検証はうまくいかず、簡単な解決策のようには見えないので、私はそれを答えとしてマークしています。 – Michael

関連する問題