使用MVC4下拉列表 [英] Dropdownlist with MVC4

查看:95
本文介绍了使用MVC4下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC的新手,我需要将数据库值填充到下拉列表中,而我需要将dropdown选中的项目保存到数据库。

我的代码



查看



 <   div     class   = 编辑标签 >  
@ Html.LabelFor(model => model.TaxID)
< / div >
< div class = editor-field > ;
@ Html.DropDownList(Tax,select Tax class)
@ Html.ValidationMessageFor(model => model.TaxID)
< / div >





控制器用于将值从数据库加载到Dropdown



 ViewBag.Tax = new SelectList(db.SHP_Taxes,TaxID,TaxName); 





保存在控制器中



 [HttpPost] 
public ActionResult NewProduct(Product newProduct)
{
if(ModelState.IsValid)
{
try
{
SHP_Product pro = new SHP_Product();
var max = db.SHP_Products.Select(x => x.ProductID).Max();
int inter = Convert.ToInt32(max);
pro.TaxID = newProduct.TaxID;
}
catch(MembershipCreateUserException e)
{


}
}
ModelState.AddModelError(,error发生);
//如果我们到目前为止,有些事情失败,重新显示形式
返回View(newProduct);
}




控制器型号中的
.taxid为null

解决方案

< blockquote>谢谢大家



 @ Html.DropDownListFor(model = >  model.TaxID,(SelectList)ViewBag.Tax)





这个适合我。谢谢你Nathan Minier ..


I am new in MVC and i need to fill database values to dropdownlist and while save i need to save dropdownselected item to database.
My code

View

<div class="editor-label">
                @Html.LabelFor(model => model.TaxID)
            </div>
            <div class="editor-field">
                @Html.DropDownList("Tax", "select Tax class")
                @Html.ValidationMessageFor(model => model.TaxID)
            </div>



controller for loading values from database to Dropdown

ViewBag.Tax = new SelectList(db.SHP_Taxes, "TaxID", "TaxName");



for Save in controller

[HttpPost]
        public ActionResult NewProduct(Product newProduct)
        {
                        if (ModelState.IsValid)
            {
                try
                {
                    SHP_Product pro = new SHP_Product();
                    var max = db.SHP_Products.Select(x => x.ProductID).Max();
                    int inter = Convert.ToInt32(max);
pro.TaxID = newProduct.TaxID;
  }
                catch (MembershipCreateUserException e)
                {


                }
            }
            ModelState.AddModelError("", "error occured");
            // If we got this far, something failed, redisplay form
            return View(newProduct);
        }



in controller model.taxid is null

解决方案

Thank you all

@Html.DropDownListFor(model => model.TaxID, (SelectList)ViewBag.Tax)



This one worked out for me. thank u Nathan Minier..


这篇关于使用MVC4下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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