在运行时MVC 5中动态地将ViewModel分配给View

时间:2016-11-22 02:20:22

标签: c# asp.net-mvc

我在MVC 5应用程序中有一个View,它有很多表单字段。对于不同的请求,我使用相同的View但不同的强类型ViewModel。每个ViewModel都具有完全相同的字段,但每种请求类型的必填字段都不同。

我的问题是,我可以根据场景在运行时动态分配强类型的ViewModel吗?我试图避免为每个场景复制相同的View,因为无论出现的场景数量如何,View都将保持一致。

例如,我想将下面的一个ViewModel分配给我创建的View,具体取决于选择的场景:

public class FirstScenario_ViewModel
{
     [Required]
     string FirstValue {get; set;}

     string SecondValue {get; set;}
}

public class SecondScenario_ViewModel
{
     string FirstValue {get; set;}

     [Required]
     string SecondValue {get; set;}
}

1 个答案:

答案 0 :(得分:0)

一种选择是重用通过不同子类的视图。 Razor甚至会识别属性并根据发送到视图的具体类型填充html。

子类化只是解决方案的一部分。第二部分是表单发布后需要发生的模型绑定。 您可以通过创建其中一个注释中提到的自定义模型绑定器来解决此问题。 另一个是调整表单的操作,以便将表单发布到可以处理正确的viewmodel类型的操作。拥有多个操作的优点是在操作上实现自定义验证变得微不足道。

使用多个操作可能不是最优雅的解决方案。我不确定是否有任何不良副作用。

以下是示例视图模型:

// This is the base class declared as the view's @model
// This one would have all the common validations
public class TestViewModel
{
    public string ModelType { get; set; }
    public virtual string Prop1 { get; set; }
    public virtual string Prop2 { get; set; }
    public virtual string Prop3 { get; set; }
}

public class TestViewModel1 : TestViewModel
{
    [Required]
    public override string Prop1 { get; set; }
}

public class TestViewModel2 : TestViewModel
{
    [Required]
    public override string Prop1 { get; set; }
    [Required]
    public override string Prop2 { get; set; }
}

控制器:

  public class TestController : Controller
{
    // GET: Test
    public ActionResult Edit(string modelType)
    {
        if (modelType == "1") return View(new Models.TestViewModel1() {ModelType = "1"});
        if (modelType == "2") return View(new Models.TestViewModel2() {ModelType = "2" });
        return View(new Models.TestViewModel() { ModelType = "" });
    }

    [HttpPost]
    public ActionResult Edit(Models.TestViewModel model)
    {
        if (model.Prop1 == null) ModelState.AddModelError("Prop1", "Please type something");
        if (ModelState.IsValid) return RedirectToAction("Edit");
        return View(model);
    }

    [HttpPost]
    public ActionResult Edit1(Models.TestViewModel1 model)
    {
        if (model.Prop1 == null || !model.Prop1.Contains("1")) ModelState.AddModelError("Prop1", "Please type at least one character 1");
        if (ModelState.IsValid) return RedirectToAction("Edit", new { modelType = "1" });
        return View("Edit", model);
    }

    [HttpPost]
    public ActionResult Edit2(Models.TestViewModel2 model)
    {
        if (model.Prop2 == null || !model.Prop1.Contains("2")) ModelState.AddModelError("Prop2", "Please type at least one character 2");
        if (ModelState.IsValid) return RedirectToAction("Edit", new { modelType = "2"});
        return View("Edit", model);
    }
}

和视图(查看 @using(Html.BeginForm .. ):

@model WebApplication1.Models.TestViewModel
@{
   Layout = null;
}
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")

@using (Html.BeginForm("Edit" + Model.ModelType, "Test", new {Model.ModelType}))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>TestModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @DateTime.Now.ToString("o")
        <br/>
        @Html.LabelFor(m => m.ModelType)
        @Html.DisplayFor(m => m.ModelType)
        <hr />
        <div class="form-group">
            @Html.LabelFor(model => model.Prop1, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Prop1, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Prop1, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Prop2, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Prop2, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Prop2, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Prop3, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Prop3, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Prop3, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>