asp.net-mvc HttpPost 上的 ASP.NET MVC DropDownList 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15709756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:42:46  来源:igfitidea点击:

ASP.NET MVC DropDownList value on HttpPost

asp.net-mvcrazorasp.net-mvc-4viewmodelhtml.dropdownlistfor

提问by Philip Tenn

I am following this Tutorial on ASP.NET MVC, specifically where it states that providing the String of "MovieType"to the Razor View as follows:@Html.DropDownList("MovieType")will provide the key to DropDownListto find a property in the ViewBagof type IEnumerable<SelectListItem>.

我正在关注ASP.NET MVC 上的这个教程,特别是它指出将字符串提供"MovieType"给 Razor 视图如下:@Html.DropDownList("MovieType")将提供DropDownList的键以查找ViewBag类型中的属性IEnumerable<SelectListItem>

That works just fine.

这工作得很好。

However, I am unable to get the value that the User selects on my method with [HttpPost]attribute.

但是,我无法获得用户在我的具有[HttpPost]属性的方法上选择的值。

Here is my code and what I have tried thus far.

这是我的代码以及迄今为止我尝试过的代码。

Controller

控制器

public class ProductController : Controller 
{
    private readonly ProductRepository repository = new ProductRepository();

    // Get: /Product/Create
    public ActionResult Create()
    {
        var categories = repository.FindAllCategories(false);
        var categorySelectListItems = from cat in categories
                                      select new SelectListItem()
                                          {
                                              Text = cat.CategoryName,
                                              Value = cat.Id.ToString()
                                          };
        ViewBag.ListItems = categorySelectListItems;
        return View();
    }

    [HttpPost]
    public ActionResult Create(Product product)
    {
        /** The following line is not getting back the selected Category ID **/
        var selectedCategoryId = ViewBag.ListItems;
        repository.SaveProduct(product);
        return RedirectToAction("Index");
    }
}

Razor cshtml View

剃刀 cshtml 视图

@model Store.Models.Product

<h2>Create a new Product</h2>

@using (@Html.BeginForm())
{
    <p>Product Name:</p>
    @Html.TextBoxFor(m => m.ProductName)

    <p>Price</p>
    @Html.TextBoxFor(m => m.Price)

    <p>Quantity</p>
    @Html.TextBoxFor(m => m.Quantity)

    <p>Category</p>
    @Html.DropDownList("ListItems")
    <p><input type="submit" value="Create New Product"/></p>
}

I tried playing with the overloads for DropDownList, but I am not able to get the value back that the User is selecting.

我尝试使用 的重载DropDownList,但我无法取回用户选择的值。

If anyone sees what I am missing or has any ideas or suggestions, I would be very grateful. Thanks!

如果有人看到我遗漏的内容或有任何想法或建议,我将不胜感激。谢谢!

Update

更新

Posting ProductModel. Note, this was auto-generated by Entity Framework when I created the .edmx.

发布Product模型。请注意,这是在我创建 .edmx 时由实体框架自动生成的。

namespace Store.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Product
    {
        public long Id { get; set; }
        public string ProductName { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }
        public System.DateTime DateAdded { get; set; }
        public Nullable<long> CategoryId { get; set; }

        public virtual Category Category { get; set; }
    }
}

回答by Peter Gluck

You are passing a model of type Store.Models.Productinto your view. The other fields are binding to this model using a lambda expression, but @Html.DropDownList()does not bind to the model so when the model is returned in the HTTPPost the selection is not there.

您正在将类型模型传递Store.Models.Product到您的视图中。其他字段使用 lambda 表达式绑定到此模型,但@Html.DropDownList()不绑定到模型,因此当模型在 HTTPPost 中返回时,选择不存在。

You need to add your Categoryfield to Store.Models.Productand then bind to that list using:

您需要使用以下方法将您的Category字段添加Store.Models.Product到该列表,然后绑定到该列表:

@Html.DropDownListFor(m => m.Category, ViewBag.ListItems)

Then MVC should properly bind your input control to the model.

然后 MVC 应该正确地将您的输入控件绑定到模型。

As an example, this syntax does work:

例如,此语法确实有效:

int[] listItems = {1, 2, 3, 4};
SelectList selectList = new SelectList(listItems);
@Html.DropDownListFor(m => m.CategoryId, selectList);

Note that SelectListinherits from MultiSelectListwhich implements IEnumerable<SelectListItem>.

请注意,SelectList继承自MultiSelectListwhich implements IEnumerable<SelectListItem>

回答by Mike C.

Follow what Peter G. has mentioned in his answer, but just for informational purposes, you should also be able to change your Post controller to this:

按照 Peter G. 在他的回答中提到的内容进行操作,但仅供参考,您还应该能够将您的 Post 控制器更改为:

[HttpPost]
public ActionResult Create(Product product, int ListItems)
{

}

As Peter has mentioned (once again, use his answer), the problem is that when your form posts, your DropDown list has a name of "ListItems" and there is nothing on your controller for it to bind to.

正如彼得所提到的(再次使用他的回答),问题是当您的表单发布时,您的下拉列表的名称为“ListItems”,并且您的控制器上没有任何东西可以绑定到它。

回答by Philip Tenn

I ended up doing the following:

我最终做了以下事情:

Controller

控制器

...
    [HttpPost]
    public ActionResult Create(Product product)
    {
        var categoryId = product.CategoryId;
        repository.SaveProduct(product);
        return RedirectToAction("Index");
    }
...

Razor cshtml View

剃刀 cshtml 视图

...
<p>Category</p>
@Html.DropDownList("CategoryId", (IEnumerable<SelectListItem>) ViewData["ListItems"])
... 

It looks ugly and to be honest, I don't fully understand why I was not able to use a lambda expression like Peter suggested, @Html.DropDownListFor(m => m.CategoryId, ViewBag.ListItems).

它看起来很丑,老实说,我不完全理解为什么我不能像 Peter 建议的那样使用 lambda 表达式,@Html.DropDownListFor(m => m.CategoryId, ViewBag.ListItems).

To me, I've "got it to work", but want to understand why, and if there is a more elegant way I can do it.

对我来说,我已经“让它工作了”,但想了解为什么,如果有更优雅的方式我可以做到。

When I typed in @Html.DropDownListFor(m => m.CategoryId, ViewBag.ListItems), IntelliSense would auto-fill m.CategoryId, but then would flag it in red, and I would get runtime error.

当我输入时@Html.DropDownListFor(m => m.CategoryId, ViewBag.ListItems),IntelliSense 会自动填充m.CategoryId,但随后会将其标记为红色,并且我会收到运行时错误。