下拉列表更好,因为ViewBag或模型C#部分/。NET MVC4 [英] Dropdown list better as ViewBag or part of model C#/.NET MVC4

查看:237
本文介绍了下拉列表更好,因为ViewBag或模型C#部分/。NET MVC4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或许简单,但我似乎失去了一些东西。

Probably simple, but I seem to be missing something.

两种型号:

public class Hardware
{
    [Required]
    public int Id { get; set; }

    public int SerialNum { get; set; }
    public int ProductNum { get; set; }
    public string Notes { get; set; }
    public DateTime PurchaseDate { get; set; }
    public DateTime WarrantyExpiration { get; set; }

    public virtual Manufacturer Manufacturer { get; set; }
}

public class Manufacturer
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual ICollection<Hardware> Hardware { get; set; }
}

当我去硬件创建视图,我希望能够从厂家的下拉列表中选择,并在其提交它应该树立的硬件和选择制造商之间的关系。

When I go to the Hardware Create view, I want to to be able to select from a dropdown of Manufacturers, and when it submits it should establish a relationship between the piece of hardware and the select Manufacturer.

目前,我一直在使用下列控制器来构建一个选择列表

At the moment, I've been using the following to build a selectList in the controller

SelectList selectList = new SelectList(db.Manufacturers, "Id", "Name");
ViewBag.selectList = selectList;

然后铸造它的观点:

And then casting it in the view:

@Html.DropDownListFor(model => model.Manufacturer, ViewBag.selectList as SelectList)\

但是,好像应该有更好的方式来做到这一点 - 也许是创建一个从硬件继承了的SelectList类型属性一个ViewModel

However, it seems like there should be a better way to do this - perhaps creating a viewModel that inherits from Hardware with a SelectList typed property?

推荐答案

随着应用程序变得越来越复杂,你会看到你的MVC应用程序变成M-VM-VC,VM是专用的ViewModels通常将所有的事情你的UI层需要以生成UI。

As your application gets more and more complicated, you will see your MVC application turning into M-VM-V-C, VM is dedicated ViewModels that usually adds all the things that your UI layer need in order to generate the UI.

我个人不会在这种情况下继承去的,因为你的视图模型是不是你的模型的专用版本。这是你的UI需要创建一个视图(这是真的给你)什么。

I personally wouldn't go with inheritance in this case, because your ViewModel is not a specialized version of your Model. It's just what your UI need to create a View (this is really up to you).

我的视图模型看起来是这样的:

My ViewModel would look something like this:

public class HardwareVm
{
     public Hardware Hardware { get; set; }
     public IEnumerable<SelectListItem> Manufacturers { get; set; }
} 

在View:

@Html.DropDownListFor(model => model.Hardware.Manufacturer,  Manufacturers)

控制器:

var manufacturers = db.Manufacturers.Select(m => new SelectListItem {Text = m.Name, Value = m.Id });
var model = new HardwareVm { Manufacturers = manufacturers };

这篇关于下拉列表更好,因为ViewBag或模型C#部分/。NET MVC4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆