MVC在回发时选择带有模型的列表,如何? [英] MVC Select List with Model at postback, how?

查看:66
本文介绍了MVC在回发时选择带有模型的列表,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MVC 3创建一个需要2个下拉列表的视图.在我唯一的其他MVC应用程序中,我们使用了Telerik控件,该控件使用Ajax方法填充数据.现在在该项目上,我们不再使用第三方控件,因此我将使用MVC SelectList进行下拉菜单.我已经阅读了很多有关如何填充SelectList的文章,但是没有一篇重复两次,总是以不同的方式创建模型,有些使用ViewDataViewBag来保存集合,传递到视图等.没有一致性.

I'm trying to create a view that will need 2 dropdown lists with MVC 3. In my only other MVC app we used the Telerik controls that used the Ajax method to populate data. Now on this project we don't use third party controls so I will be using the MVC SelectList for dropdowns. I've been reading a lot of articles on how to populate a SelectList but none of them say the same thing twice, always a different way to create the model, some use ViewData or ViewBag to hold the collections and pass to the view, etc.. no consistency.

在MVC视图中填充下拉列表的最佳方法是什么,该视图使用模型本身作为数据,而不是ViewData.当用户从列表中进行选择,提交并调用HttpPost动作时,如何从选择列表属性的模型"属性中访问选择的值?

What is the best accepted method to populate a dropdown in an MVC view that uses the model itself for the data, not ViewData. And when the user makes a selection from the list, submits and the HttpPost action is called, how do I access the selected value from the Model property of the select list property?

这是我当前的型号:

public class TemporaryRegistration {
    [Required]
    [Email(ErrorMessage = "Please enter a valid email address.")]
    [Display(Name = "Email address")]
    public string Email { get; set; }

    [Required]
    [Integer]
    [Min(1, ErrorMessage = "Please select an entity type.")]
    [Display(Name = "Entity Type")]
    public IEnumerable<SelectListItem> EntityType { get; set; }

    [Required]
    [Integer]
    [Min(1, ErrorMessage = "Please select an associated entity.")]
    [Display(Name = "Associated Entity")]
    public IEnumerable<SelectListItem> AssociatedEntity { get; set; }
}

这是我当前的视图,只在需要使用下拉菜单的地方使用TextBoxFor,如何将它们变成下拉菜单?

This is my current view, it's only using TextBoxFor where I need to use the dropdowns, how do I turn them into dropdowns?

@model Web.Models.TemporaryRegistration

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
    <legend>Create New ELM Select User</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.EntityType)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EntityType)
            @Html.ValidationMessageFor(model => model.EntityType)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.AssociatedEntity)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.AssociatedEntity)
            @Html.ValidationMessageFor(model => model.AssociatedEntity)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

这是我当前的发布操作: 如何获取选定的值?

This is my current Post action: How do I get the selected values out?

[HttpPost]
public ActionResult CreateUser(TemporaryRegistration registrationModel) {
    string newRegistrationGUID = string.Empty;
    if (!ModelState.IsValid) {
        return View();
    }

    TemporaryRegistrationEntity temporaryRegistration = null;
    temporaryRegistration = new TemporaryRegistrationEntity(registrationModel.Email, registrationModel.EntityType, registrationModel.AssociatedEntity);
    newRegistrationGUID = temporaryRegistration.Save();
    return Content("New registration was created with GUID " + newRegistrationGUID);
}

推荐答案

从注释继续...

假设您有一个名为Toy的模型.玩具具有NamePriceCategory之类的属性:

Let's say you have a Model called Toy. Toy has properties like Name, Price, and Category:

public class Toy()
{
    public string Name;
    public double Price;
    public string Category
}

现在,您想构建一个表单视图以添加Toy,人们需要能够从可能的下拉菜单中选择一个类别...但是您不想通过ViewData来做到这一点.或ViewBag由于某种原因.

Now you want to build a form View to add a Toy, and people need to be able to select a category from a drop down of possibilities... but you don't want to do this via ViewData or ViewBag for some reason.

创建一个具有NamePriceCategory ...的ToyViewModel,而不是将模型传递给视图,而不是将 包含要填充的类别的集合.下拉:

Instead of passing the Model to the View, create a ToyViewModel that has Name, Price, Category... but also has a collection of categories to populate the drop down:

public class ToyViewModel()
{
    public string Name;
    public double Price;
    public string Category

    public ICollection<string> Categories;
}

现在,您的控制器将执行此操作:

Now your controller does this:

public ActionResult GetToyForm()
{
    var viewModel = new ToyViewModel();
    viewModel.Categories = _service.GetListOfCategories();
    return View(viewModel);
}

您的视图已绑定到ViewModel,并且您使用model.Categories集合填充了下拉菜单.其外观应类似于:

Your View is bound to the ViewModel, and you use the model.Categories collection to populate your dropdown. It should look something like:

@Html.DropDownListFor(model => model.Category, model.Categories)

提交时,您的控制器会执行以下操作:

When you submit it, your controller does something like:

[HttpPost]
public ActionResult CreateToy(ToyViewModel _viewModel)
{
    var model = new Toy();
    model.Name = _viewModel.Name
    // etc.

    _service.CreateToy(model);

    // return whatever you like.
    return View();
}

将ViewModels绑定到Views是一个好习惯,这样您就可以根据表示层的需求对其进行定制,同时让Models保持与数据层和业务逻辑的紧密联系.

It is good practice to make ViewModels for binding to Views so you can tailor them to the needs of your presentation layer, while having your Models remain close to the data layer and business logic.

这篇关于MVC在回发时选择带有模型的列表,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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