如何从ASP.NET MVC3中的下拉中访问选定的项目



我正在使用ASP.NET MVC3,我使用以下模型填充创建视图

模型

public class CategoryModel
{
    public  int Id { get; set; }
    public string Name { get; set; }
    public  string URL { get; set; }
    public  string Description { get; set; }
    public  string Logo { get; set; }
    public  bool IsActive { get; set; }
    public  bool isPopular { get; set; }
    public IList<Category> Parentcategories { get; set; }
}

在我的创建视图中,我像这样填充了

查看

 <div class="editor-field">
        @Html.DropDownList("parentcategories", new SelectList(Model.Parentcategories.Select(c => c.Name), Model.Parentcategories.Select(c => c.Name)))
        @Html.ValidationMessageFor(model => model.Parentcategories)
    </div>

现在如何在控制器方法中访问所选项目

方法

 [HttpPost]
    public ActionResult Create( CategoryModel model , HttpPostedFileBase file)
    {
     // 
    }

谢谢Ahsan

尝试以下:

public ActionResult Create(string parentcategories, CategoryModel model , HttpPostedFileBase file)

parentcategories将包含选定的option值。

AS smartboy 已经提到了,您应该使用dropdownlistfor:
1.用public int ParentCategoryId { get; set; }字段附加模型。
2.而不是使用 @html.dropdownlist使用:
@Html.DropDownListFor(m => m.ParentCategoryId, new SelectList(...))
3.服务器端可以保持不变:

[HttpPost]
public ActionResult Create(CategoryModel model)
{
   // 
}

model.ParentCategoryId将选择项目值。
另请注意,您可以首先设置视图的选定项目值:

public ActionResult Index()
{
  var model = CategoryModel();
  ...
  model.ParentCategoryId = some_selected_value;
  return View(model);
}

详细信息:您可以直接从模型访问。

[HttpPost]
public ActionResult Create( CategoryModel model , HttpPostedFileBase file)
{
      var selectedCategory = model.parentcategories;  // something like that
}

最新更新