【问题标题】:How to get data from a partial view ViewModel in to the main ViewModel如何从部分视图 ViewModel 获取数据到主 ViewModel
【发布时间】:2019-04-27 00:42:34
【问题描述】:

我正在使用 ASP.net MVC5 创建一个 POC 应用程序。我想要一个顶级视图模型,其中包含部分视图中所有视图模型的数据。但是,当我提交表单时,它不会将模型中的数据传递到顶层,这是我有些预期但不想发生的。

查看模型

public class InvoiceViewModel
{
    public InvoiceInfo InvoiceInfo { get; set; }
}

public class InvoiceInfo
{
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime DateRaised { get; set; } = DateTime.Now;
    public int InvoiceNo { get; set; }
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }
    public Currency InvoiceCurrency { get; set; }
}

表单提交功能

[HttpPost]
public ActionResult CreateInvoice(InvoiceInfo vm)
{
    if (ModelState.IsValid)
    {
        vm.FromDate = vm.ToDate;
    }

    return View(vm);
}

使用“InvoiceViewModel”的主 razer 视图

@using (Html.BeginForm("CreateInvoice", "Invoice", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.Partial("_InvoiceInfo", Model.InvoiceInfo)

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

部分视图'_InvoiceInfo'

<div class="form-horizontal">
    <h4>InvoiceInfo</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.DateRaised, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DateRaised, new { htmlAttributes = new { @class = "form-control datepicker" } })
            @Html.ValidationMessageFor(model => model.DateRaised, "", new { @class = "text-danger" })
        </div>
    </div>

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

因此,当我单击提交时,我希望 InvoiceInfo 对象包含所有相关数据的 InvoiceViewModel 对象。这可能是不可能的,但我们将不胜感激。

【问题讨论】:

  • 你应该使用InvoiceViewModel 来代替CreateInvoice 方法,因为你提交的表单使用了InvoiceViewModel,那么如果你在部分创建表单标签并提交你的代码是正确的。
  • 我知道你在这里得到了什么,但我只想提交这个功能的顶级表单

标签: c# asp.net-mvc razor


【解决方案1】:

更容易做到InvoiceInfo : InvoiceViewModel。 Razor @model InvoiceViewModel 这样你就拥有了两个模型的所有属性。

【讨论】:

  • 继承在这里不起作用,因为它会使后续处理变得非常困难,因为我需要将其结构化到 XML 文档中。
  • 继承有效,但可能很难管理所有数据。您可以使用属性 ViewBag。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 2017-11-06
  • 2020-12-31
  • 1970-01-01
  • 2013-02-04
  • 2020-06-26
  • 1970-01-01
相关资源
最近更新 更多