0

我有一个问题,我有两个相同的表单,除了必填字段不同。例如,假设表单具有相同的字段:X、Y 和 Z。在 Form #1 中,X 是必需的,但在 Form #2 中,Y 是必需的。

所以我创建了两个视图模型,Form1 和 Form2,它们具有相同的属性,但在不同的属性上具有所需的属性。然后我创建了一个接口,我们称之为 IForm,两个模型都实现并构建了一个在 IForm 上强类型化的视图。

该解决方案的问题是 ASP.NET MVC 3 读取 IForm 上的属性而不是传递给视图的对象的动态类型,即 Form1 或 Form2,因此我没有得到客户端 JavaScript 字段验证我想。

我想知道除了为每个视图模型创建强类型视图之外是否还有其他解决方案。

4

2 回答 2

2

我已经根据您的描述(我认为)整理了一个样本,并且我能够让它工作:

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

然后我定义了一个强类型视图:

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

当我浏览到 /test/foo 并点击保存时,我在名称上收到验证错误。

当我浏览到 /test/bar 并点击保存时,我在描述中收到验证错误。

于 2011-07-26T21:04:47.590 回答
0

尝试部分表单验证方法。

http://softwaredevelopmentsolutions.blogspot.com/2011/06/aspnet-mvc-3-partial-form-validation-on.html

创建自定义操作过滤器属性。用它装饰操作方法以根据表单忽略验证属性。

于 2011-07-27T04:13:44.220 回答