asp.net-mvc 如何在MVC中的控制器中获取下拉值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18548039/
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 03:08:52  来源:igfitidea点击:

How to get drop down value in Controller in MVC

asp.net-mvcasp.net-mvc-3asp.net-mvc-4

提问by user1035814

I Bind dropdown using list of string using recursive function
My dropdown have value like Home Home>> Kitchen Home>> Kitchen>> ABC

我使用递归函数使用字符串列表绑定下拉列表
我的下拉列表具有像 Home Home>> Kitchen Home>> Kitchen>> ABC 这样的值

and i want to Same dropdown value ABC in database

我想在数据库中使用相同的下拉值 ABC

This is my View code

这是我的查看代码

@{
    ViewBag.Title = "Createnewproduct";
}
<h2>
    Create new product</h2>
<div>
    @using (Html.BeginForm("Createnewproduct", "ProductAdmin", FormMethod.Post, new { id = "sendFileForm", enctype = "multipart/form-data" }))
    {
        <table>
            <tr>
                <td>
                    Category
                </td>
                <td>
                    @Html.DropDownList("Test", new SelectList(ViewBag.ListOfDisciplines, Model))
                </td>
            </tr>
            <tr>
                <td>
                    Product Name
                </td>
                <td>
                    <input type="text" name="ProductName">
                </td>
            </tr>
            <tr>
                <td>
                    Product Description
                </td>
                <td>
                    <input type="text" name="ProductDescription">
                </td>
            </tr>
            <tr>
                <td>
                    Product long Description
                </td>
                <td>
                    <input type="text" name=" ProductlongDescription">
                </td>
            </tr>
            <tr>
                <td>
                    UPC
                </td>
                <td>
                    <input type="text" name="UPC">
                </td>
            </tr>
            <tr>
                <td>
                    SKU
                </td>
                <td>
                    <input type="text" name="SKU">
                </td>
            </tr>
            <tr>
                <td>
                    Stock
                </td>
                <td>
                    <input type="text" name="Stock">
                </td>
            </tr>
            <tr>
                <td>
                    Weight
                </td>
                <td>
                    <input type="text" name="Weight">
                </td>
            </tr>
            <tr>
                <td>
                    Height
                </td>
                <td>
                    <input type="text" name="Height">
                </td>
            </tr>
            <tr>
                <td>
                    Image URL
                </td>
                <td>
                    <input type="file" name="file" id="file" style="width: 100%;" id="Imageupload" />
                </td>
            </tr>
            <tr>
                <td rowspan="2">
                    <input type="submit" value="Save" />
                </td>
            </tr>
        </table>
    }
</div>

and my controller like this

我的控制器是这样的

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Createnewproduct(FormCollection form)
        {

        }

when i see my FormCollection value there i did not find dropdown value , all other value properly find in FormCollection

当我看到我的 FormCollection 值时,我没有找到下拉值,所有其他值都在 FormCollection 中正确找到

Please help me where i did the mistake in this code

请帮助我在此代码中的错误位置



 public ActionResult Createnewproduct()
    {
        List<Category> categorylist = _Listofcategory();
        var parentcate = categorylist.Where(c => c.ParentCategoryId == 1).ToList();
        List<String> categoryList = new List<string>();
        string prefix = ">>";
        foreach (var item in parentcate)
        {
            prefix = item.CategoryName;
            Setchild(prefix, item, categorylist, categoryList);


        }

        ViewBag.ListOfDisciplines = categoryList;
        return View();
    }


    private void Setchild(string prefix, Category model, List<Category> listcategory, List<string> catStrings)
    {
        var childs = listcategory.Where(x => x.ParentCategoryId == model.CategoryId).ToList();

        catStrings.Add(prefix);
        if (childs.Count > 0)
        {

            foreach (var child in childs)
            {
                catStrings.Add(prefix + ">>" + child.CategoryName);
                var subchild = listcategory.Where(c => c.ParentCategoryId == child.CategoryId).ToList();
                if (subchild.Count > 0)
                {
                    foreach (var subsubchild in subchild)
                    {
                        catStrings.Add(prefix + ">>" + child.CategoryName + ">>" + subsubchild.CategoryName);

                        var subsubsubchild = listcategory.Where(c => c.ParentCategoryId == subsubchild.CategoryId).ToList();
                        if (subsubsubchild.Count > 0)
                        {
                            foreach (var subsubsubsubchild in subsubsubchild)
                            {
                                catStrings.Add(prefix + ">>" + child.CategoryName + ">>" + subsubchild.CategoryName + ">>" + subsubsubsubchild.CategoryName);
                            }
                        }
                    }
                }


            }

        }

    }

This my List of Category how to use in View model.

这是我的类别列表如何在视图模型中使用。

Please let me know

请告诉我

回答by Sampath

You can use below mentioned sample code for your scenario as well.Here I have used ViewModel.

您也可以将下面提到的示例代码用于您的场景。这里我使用了 ViewModel。

Domain Models :

领域模型:

 public class Product
    {
        public Product() { Id = Guid.NewGuid(); Created = DateTime.Now; }
        public Guid Id { get; set; }
        public string ProductName { get; set; }

        public virtual ProductCategory ProductCategory { get; set; }
    }

 public class ProductCategory
    {
        public int Id { get; set; }
        public string CategoryName { get; set; }

        public virtual ICollection<Product> Products { get; set; }
    }

View Model :

查看型号:

public class ProductViewModel
    {
        public Guid Id { get; set; }

        [Required(ErrorMessage = "required")]
        public string ProductName { get; set; }

        public int SelectedValue { get; set; }

        public virtual ProductCategory ProductCategory { get; set; }

        [DisplayName("Product Category")]
        public virtual ICollection<ProductCategory> ProductCategories { get; set; }
    }

Action Methods :

行动方法:

 [HttpGet]
        public ActionResult AddProduct() //generate view with categories for enter product data
        {
            //for get product categories from database
            var prodcutCategories = Repository.GetAllProductCategories();

            //for initialize viewmodel
            var productViewModel = new ProductViewModel();

            //assign values for viewmodel
            productViewModel.ProductCategories = prodcutCategories;

            //send viewmodel into UI (View)
            return View("AddProduct", productViewModel);
        }

        [HttpPost]
        public ActionResult AddProduct(ProductViewModel productViewModel) //save entered data
        {
            //get product category for selected drop down list value
            var prodcutCategory = Repository.GetProductCategory(productViewModel.SelectedValue);

            //for get all product categories
       var prodcutCategories = Repository.GetAllProductCategories();

            //for fill the drop down list when validation fails 
             productViewModel.ProductCategories = prodcutCategories;

            //for initialize Product domain model
            var productObj = new Product
                                     {
                                         ProductName = productViewModel.ProductName,
                                         ProductCategory = prodcutCategory,
                                     };

            if (ModelState.IsValid) //check for any validation errors
            {
                //save recived data into database
                Repository.AddProduct(productObj);
                return RedirectToAction("AddProduct");
            }
            else
            {
                //when validation failed return viewmodel back to UI (View) 
                return View(productViewModel);
            }
        }

View :

看法 :

@model YourProject.ViewModels.ProductViewModel        //set your viewmodel here

 <div class="boxedForm">

@using (Html.BeginAbsoluteRouteForm("add", new { action = "AddProduct"},FormMethod.Post }))
         {
             <ul>
                     <li style="width: 370px">
                           @Html.LabelFor(m => m.ProductCategories)
   @Html.DropDownListFor(m => m.SelectedValue,new SelectList(Model.ProductCategories, "Id",
                                             "CategoryName"),"-Please select a category -")
                           @Html.ValidationMessageFor(m => m.ProductCategory.Id)
                    </li>
                    <li style="width: 370px">
                  @Html.CompleteEditorFor(m => m.ProductName, labelOverride: "Product Name")
                  @Html.ValidationMessageFor(m => m.ProductName) 
                    </li>
            </ul>
                    <div class="action">
                        <button class="actionButton" type="submit">
                            <span>Save</span></button>
                    </div>
         }
   </div>

Final Output

最终输出

enter image description here

在此处输入图片说明

If you have any problem about above code snippets,Plz let me know. I have written whole article about ViewModel,It's here :How to Use ViewModel with ASP.NET MVC .

如果您对上述代码片段有任何问题,请告诉我。我写了整篇关于 ViewModel 的文章,它在这里:如何在 ASP.NET MVC 中使用 ViewModel

I hope this will help to you.

我希望这会对你有所帮助。

回答by Roger Barreto

Assuming your ViewBag.ListOfDisciplinesis a List<Discipline>and your Discipline class is:

假设您ViewBag.ListOfDisciplines是 aList<Discipline>并且您的 Discipline 类是:

public class Discipline {
     public int Id { get; set; }
     public string Name { get; set; }
}

If you have a List of strings you could transform it in a Array of anonymous in the controller side

如果您有一个字符串列表,您可以将其转换为控制器端的匿名数组

ViewBag.ListOfDIsciplines = from d in ListDisciplines select new { Id = d, Name = d };

In your view you should use

在您看来,您应该使用

@Html.DropDownList("Test", new SelectList(ViewBag.ListOfDisciplines, "Id", "Name"), "-- Select here --")