本文介绍了我如何使用editortemplates在MVC3复杂的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班,增值税和产品。产品具有IVat的属性。我想使用的编辑器模板MVC创建/编辑产品时显示所有的还原对象的下拉列表。对于我的亲爱的生活,我不能得到这个工作。

I have two classes, Vat and Product. Product has a property of IVat. I am trying to use editor templates in MVC to display a dropdown list of all the Vat objects when creating/editing a Product. For the dear life of me I cannot get this working.

我有以下的code,其显示的下拉但是当表单被提交它不设置瓮的产品。

I have the following code which displays the dropdown but it does not set the Vat for the Product when the form gets submitted.

控制器:

IList<IVatRate> vatRates = SqlDataRepository.VatRates.Data.GetAllResults();
ViewBag.VatRates = new SelectList(vatRates, "Id", "Description");

Add.cshtml

Add.cshtml

@Html.EditorFor(model => model.VatRate.Id, "VatSelector", (SelectList)ViewBag.VatRates)

VatSelector.cshtml

VatSelector.cshtml

@model SelectList
@Html.DropDownList(
        String.Empty /* */,
            (SelectList)ViewBag.Suppliers,
        Model
    )

我将不胜感激,如果任何人都可以阐明这一些轻,甚至点我到网上的某个地方......我一直在坚持这一相当,现在几天就一个很好的例子。

I would be grateful if anyone can shed some light on this or even point me to a good example on the web somewhere...I have been stuck with this for quite a few days now.

推荐答案

,因为它使事情这么多,而不是ViewBag,更容易我会使用强类型的视图和视图模型

I would use strongly typed views and view models as it makes things so much easier rather than ViewBag.

因此​​,与视图模型启动:

So start with a view model:

public class VatRateViewModel
{
    public string SelectedVatRateId { get; set; }
    public IEnumerable<IVatRate> Rates { get; set; }
}

然后控制器:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new VatRateViewModel
        {
            Rates = SqlDataRepository.VatRates.Data.GetAllResults()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(VatRateViewModel model)
    {
        // model.SelectedVatRateId will contain the selected vat rate id
        ...
    }
}

查看:

@model VatRateViewModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(
        x => x.SelectedVatRateId,
        new SelectList(Model.Rates, "Id", "Description")
    )
    <input type="submit" value="OK" />
}

如果你想使用的编辑器模板的VatRateViewModel你可以定义一个在〜/查看/共享/ EditorTemplates / VatRateViewModel.cshtml

@model VatRateViewModel
@Html.DropDownListFor(
    x => x.SelectedVatRateId,
    new SelectList(Model.Rates, "Id", "Description")
)

然后,每当某个地方你有类型的属性 VatRateViewModel 您可以简单:

@Html.EditorFor(x => x.SomePropertyOfTypeVatRateViewModel)

这将使得相应的编辑器模板。

which would render the corresponding editor template.

这篇关于我如何使用editortemplates在MVC3复杂的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:52