Asp.Net MVC3 - 如何创建动态的DropDownList [英] Asp.Net MVC3 - How create Dynamic DropDownList

查看:151
本文介绍了Asp.Net MVC3 - 如何创建动态的DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个文章很多,但仍然我不知道究竟是如何做到这一点。我想创建自己的博客引擎,我查看了创建的文章(我使用的EF和code第一),现在我必须填写类别的数量,其中的文章应该被添加,但我想改变它DROPDOWNLIST同类别的名称。我的模型看起来这样的:

I found many articles on this but still I don´t know how exactly to do this. I am trying to create my own blog engine, I have View for create article (I am using EF and Code first) and now I must fill number of category in which article should be add but I want to change it to dropdownlist with names of categories. My model looks this:

public class Article
{
    public int ArticleID { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public int CategoryID { get; set; }
    public DateTime Date { get; set; }
    [Required()]
    [DataType(DataType.MultilineText)]
    [AllowHtml]
    public string Text { get; set; }
    public virtual Category Category { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}
public class Category
{
    public int CategoryID { get; set; }
    [Required]
    public string Name { get; set; }
    public virtual ICollection<Article> Articles { get; set; }

}

我知道我必须使用枚举(或我认为),但我不完全知道如何。我不知道从教程,我发现最适合我。

I know I must use Enum (or I think) but I am not exactly sure how. I don´t know which tutorial from that I found is best for me.

编辑:

谢谢您的回答,但我发现别的东西。我想这样的:

Thanks for your answers but I found something else. I am trying this:

这是我的模型:

public class Article
{
    [Key]
    public int ArticleID { get; set; }

    [Display(Name = "Title")]
    [StringLength(30, MinimumLength = 5)]
    [Required]
    public string Title { get; set; }

    public DateTime Date { get; set; }

    public int CategoryID { get; set; }

    [Required()]
    [DataType(DataType.MultilineText)]
    [AllowHtml]
    public string Text { get; set; }

   public Category Category { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }

    public IEnumerable<Category> Categories { get; set; }
}
public class Category
{
[Key]
    public int CategoryId { get; set; }
    [Required]
public string CategoryName { get; set; }
    public virtual ICollection<Article> Articles { get; set; }

}

这是我的控制器来创建文章:

This is my controller to create article:

public ActionResult Vytvorit()
{
    IEnumerable<Category> categories = GetCaregories();
    var view = View(new Article() { Categories = categories });
    view.TempData.Add("Action", "Create");

    return view;

}

private static IEnumerable<Category> GetCaregories()
{
    IEnumerable<Category> categories;
    using (BlogDBContext context = new BlogDBContext())
    {
        categories = (from one in context.Categories
                      orderby one.CategoryName
                      select one).ToList();
    }
    return categories;
}

private Category GetCategory(int categoryID)
{
        return db.Categories.Find(categoryID);
}
//
// POST: /Clanky/Vytvorit

[HttpPost]
public ActionResult Vytvorit(Article newArticle)
{

    try
    {
        if (newArticle.CategoryID > 0)
        {
            newArticle.Category = GetCategory(newArticle.CategoryID);
        }
        if (TryValidateModel(newArticle))
        {
                db.Articles.Add(newArticle);
                db.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            newArticle.Categories = GetCaregories();
            var view = View(newArticle);
            view.TempData.Add("Action", "Create");
            return view;
        }
    }
    catch
    {
        return View();

    }
}

这是我的部分观点:

And this is part of my view:

     @Html.DropDownListFor(model => model.CategoryID, new SelectList(Model.Categories,"CategoryID","CategoryName"))
        @Html.ValidationMessageFor(model => model.CategoryID)

我有NullReferenceExeption问题,但我不知道为什么。我能做到这样?它看起来对我来说很容易。

I have problem with NullReferenceExeption but I don´t know why. Can I do it this way? It looks very easy for me.

推荐答案

您模式似乎很奇怪。它包含的属性,如类别id 类别这似乎是多余的。它还包含称为 SelectListItem 集合属性类别。所以,这是一个模型或视图模型?看起来蛮混乱。让我们假设这是一个典范。在这种情况下,它更可能是这个样子:

Your model seems quite strange. It contains properties such as CategoryID and Category which seem redundant. It also contains a SelectListItem collection property called Categories. So, is this a model or a view model? It looks quite messed up. Let's assume it's a model. In this case it would more likely look something like this:

public class Article
{
    public int ArticleID { get; set; }

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

    public DateTime Date { get; set; }

    [Required()]
    [DataType(DataType.MultilineText)]
    [AllowHtml]
    public string Text { get; set; }

    public virtual Category Category { get; set; }

    public IEnumerable<Category> Categories { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
}

public class Category
{
    public int CategoryID { get; set; }

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

    public virtual ICollection<Article> Articles { get; set; }

}

现在,该模型是明确的,我们可以定义将被传递到视图的视图模型。视图模型是这是专门为视图设计的一类。所以,这取决于你打算把这个观点你在这个视图模型中定义它是什么。到目前为止,您已经讲过只有一个下拉,让我们做到这一点:

Now that the model is clear we could define a view model which will be passed to the view. A view model is a class which is specifically designed for the view. So depending on what you intend to put in this view you define it in this view model. So far you have talked only about a drop down, so let's do it:

public class ArticleViewModel
{
    public int SelectedCategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; }
}

,然后我们有一个控制器:

and then we have a controller:

public class ArticlesController: Controller
{
    private readonly IArticlesRepository _repository;
    public ArticlesController(IArticlesRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        Article article = _repository.GetArticle();
        ArticleViewModel viewModel = Mapper.Map<Article, ArticleViewModel>(article);
        return View(viewModel);
    }
}

于是控制器使用存储库来获取模式,它映射到一个视图模型(在这个例子中我使用 AutoMapper ),并通过该视图模型将于显示它照顾的看法:

So the controller uses a repository to fetch the model, maps it to a view model (in this example I use AutoMapper) and passes the view model to the view which will take care of showing it:

@model AppName.Models.ArticleViewModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(
        x => x.SelectedCategoryId, 
        new SelectList(Model.Categories, "Value", "Text"),
        "-- Select category --"
    )
    <input type="submit" value="OK" />
}

这篇关于Asp.Net MVC3 - 如何创建动态的DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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