【问题标题】:How to get drop down value in Controller in MVC如何在 MVC 中的 Controller 中获取下拉值
【发布时间】:2013-08-31 12:16:50
【问题描述】:

我使用递归函数使用字符串列表绑定下拉列表
我的下拉菜单具有类似的价值 家 首页>> 厨房 首页>> 厨房>> ABC

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

这是我的查看代码

@{
    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>

和我的控制器这样

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

        }

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

请帮助我在这段代码中哪里出错了


 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);
                            }
                        }
                    }
                }


            }

        }

    }

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

请告诉我

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

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

领域模型:

 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; }
    }

查看模型:

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; }
    }

动作方法:

 [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);
            }
        }

查看:

@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>

最终输出

【讨论】:

  • 嗨 Sampath,我认为它应该适合我。我稍后会先更新你我会尝试实现这个..感谢你的帮助
  • @user1035814 好的。如果您有任何问题,请花点时间告诉我。如果有,我会为您提供帮助。 :)
  • 谢谢你 Sampath :) 你真的很了解 MVC。我只是 MVC 的初学者,从 MVC 的音乐商店学习,并想创建电子商务网站 .. 感谢您帮助我 :)
  • @user1035814 很高兴听到它有帮助。如果您需要更多帮助,请告诉我。您可以通过 StackOverFlow Profile (stackoverflow.com/users/1077309/sampath) 找到我的详细信息。祝你好运!
【解决方案2】:

假设您的 ViewBag.ListOfDisciplinesList&lt;Discipline&gt; 并且您的 Discipline 课程是:

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

如果你有一个字符串列表,你可以在控制器端将它转换成一个匿名数组

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

在你看来你应该使用

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

【讨论】:

  • 嗨,罗杰,纪律是字符串列表,所以我认为它不起作用。请参阅下面的代码。我在下拉列表中绑定
  • @user1035814,好的,为您的组合生成的 View HTML 代码是什么?
  • @user1035814,如您所见,您的选项没有价值,这就是您的问题的根源,尝试使用我的方法并使用字符串列表,您使用 LINQ 代替(更新的响应)
  • No Rozar 选项的值为 Home1 , Home1 .... 填充在我的 dropdowon 列表中
猜你喜欢
  • 2023-03-04
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多