简体   繁体   English

下拉列表asp.net

[英]Dropdownlist asp.net

I have an application that allows user to create new items. 我有一个允许用户创建新项目的应用程序。 As it stands now the user need to fill out Title, body and category. 现在,用户需要填写标题,正文和类别。

The category is a textbox but I would like to convert it to a dropdownlist. 该类别是一个文本框,但我想将其转换为下拉列表。 This is all connected to a database and when the user submits it the data should be saved in the database. 这些都连接到数据库,并且当用户提交数据库时,数据应该保存在数据库中。 Everything works fine as it stands now, I am only having trouble implementing the dropdownlist. 现在一切正常,我在实现下拉列表方面遇到了麻烦。

My model: 我的模特:

 public class NewsItem
    {
        public int ID { get; set; }
        [Required(ErrorMessage = "Title is Required")] 
        public string Title { get; set; }
         [Required(ErrorMessage = "Body is Required")] 
        public DateTime DateCreate { get; set; }
        public string Category { get; set; }
    }

What is the quickest/best way implementing this. 最快/最好的方法是什么? Should I do it in the model or can I assign the values available in the view? 我应该在模型中执行此操作,还是可以分配视图中可用的值?

Thanks in advance! 提前致谢!

First, some semantics. 首先,一些语义。 Since Entity Framework comes along with MVC, the assumption is that your POCOs are "models". 由于Entity Framework是随MVC一起提供的,因此假设您的POCO是“模型”。 (Unfortunately, Microsoft kind of piles on by putting scaffolded POCOs in a "Models" folder). (不幸的是,Microsoft通过将脚手架POCO放在“模型”文件夹中而积累了很多东西)。 However, these are not models in terms of the "Model" in Model-View-Controller; 但是,就Model-View-Controller中的“模型”而言,这些不是模型。 instead, they are merely "entities", which is a fancy way of saying "pretty much just a DTO EF can use to stuff data from the database into." 相反,它们仅是“实体”,这是一种说法,“ DTO EF几乎可以用来将数据库中的数据填充到其中”。

I point that out to say this: no, you shouldn't put your drop down list choices on your entity . 我指出这一点是:不,您不应该将下拉列表选项放在实体上 But, you shouldn't rely on the view for this either. 但是,您也不应该为此依赖视图。 What you really want here is a view model. 您真正想要的是视图模型。 You create a class that has just the fields you need to edit and any additional business logic your view needs (such as the choices of categories), and then you map your entity to and from this view model. 您创建一个类,其中仅包含您需要编辑的字段以及视图所需的任何其他业务逻辑(例如类别的选择),然后将您的实体与该视图模型进行映射。 As an example: 举个例子:

public class NewsItemViewModel
{
    [Required(ErrorMessage = "Title is Required")] 
    public string Title { get; set; }

    [Required(ErrorMessage = "Body is Required")] 
    public DateTime DateCreate { get; set; }

    public string Category { get; set; }

    public IEnumerable<SelectListItem> CategoryChoices { get; set; }
}

Notice that while this class is mostly the same, it doesn't contain an Id property, because this is not something you'd want the user to edit. 请注意,虽然这个类是几乎相同,它不包含Id属性,因为这不是你想要的用户做一些修改。 Also, it includes a CategoryChoices property to hold the items for your drop down list. 此外,它还包含一个CategoryChoices属性,用于保存下拉列表中的项目。

Then in your controller, you would do something like: 然后在您的控制器中,您将执行以下操作:

public ActionResult CreateNewsItem()
{
    var model = new NewsItemViewModel();
    model.CategoryChoices = db.Categories.Select(m => new SelectListItem { Value = m.Name, Text = m.Name });
    return View(model);
}

Basically, you're just newing up the view model so you can feed it to the view. 基本上,您只是在更新视图模型,以便可以将其提供给视图。 You fill in your category choices before actually returning it, though. 不过,您需要在实际返回之前填写类别选择。 I've assumed they're also entities, but you would use whatever method you needed to fetch them here, otherwise. 我假设它们也是实体,但是您可以使用所需的任何方法在这里获取它们,否则。

For your post action: 对于您的帖子操作:

[HttpPost]
public ActionResult CreateNewsItem(NewsItemViewModel model)
{
    if (ModelState.IsValid)
    {
        // map view model to entity
        var newsItem = new NewsItem
        {
            Title = model.Title,
            Category = model.Category,
            // and so on
        }

        db.NewsItems.Add(newsItem);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    model.CategoryChoices = db.Categories.Select(m => new SelectListItem { Value = m.Name, Text = m.Name });
    return View(model);
}

I'm just doing a manual mapping from the view model to a new news item, here, but for real world scenarios, you'd probably want to integrate a mapping library for this, such as AutoMapper. 我只是在这里进行从视图模型到新新闻项的手动映射,但是对于现实世界的场景,您可能希望为此集成一个映射库,例如AutoMapper。 Also, take note that in the case where there's an error, you must refill the category choices before returning the view again. 另外,请注意,如果出现错误,您必须重新填写类别选择,然后再次返回视图。 These will not be posted by your form, so the model that was passed in will not have them. 这些不会通过您的表单发布,因此传入的模型将不会包含它们。

Finally, in your view: 最后,您认为:

@model Namespace.To.NewsItemViewModel

...

@Html.DropDownListFor(m => m.Category, Model.CategoryChoices)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM