Asp.net MVC 3 - 来自具有selectedvalue的数据库的下拉列表 [英] Asp.net MVC 3 - dropdownlist from database with selectedvalue

查看:56
本文介绍了Asp.net MVC 3 - 来自具有selectedvalue的数据库的下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC的新手,我想知道是否有人可以请求帮助?



我有以下内容填充模型中每行的DropDownList但是没有填充页面时,在DropDownList中设置所选值(tblcusts.typeid)。任何帮助将不胜感激。



我尝试过:



模型

I am new to MVC and am wondering if someone can please help?

I have the following which populates the DropDownList for each row in the model yet does not set the selected value (tblcusts.typeid) in the DropDownList when the page is populated. Any assistance would be greatly appreciated.

What I have tried:

Models

public class tblcusts
{
   [Key]
   public int custid { get; set; }
   public int typeid { get; set; }
}

public class tblcusttypes
{
  [Key]
  public int typeid { get; set; }
  public string name { get; set; }
  public bool active { get; set; }
}



查看


View

@Model IList<MvcApplication1.Models.tblcusts>
@for (var i = 0; i < Model.Count; ++i)
    {
       @Html.DropDownList("typeid", (IEnumerable<SelectListItem>)ViewBag.customertype)
       <br />
    }



控制器


Controller

var result = from m1 in db.custs select m1;

var query = from m2 in db.custtypes where m2.active == true orderby m2.name select m2.name;
var CustomerTypeList = new List<string>();
CustomerTypeList.AddRange(query.Distinct());
ViewBag.customertype = new SelectList(CustomerTypeList);

return View(result.ToList());

推荐答案

您没有获得所选值,因为您的没有设置任何选定的值。此外,您的视图令人困惑,您在视图中的下拉列表中循环,您应该在您的模型或控制器(最好是型号)中执行此操作....但不是我猜它会显示每个客户的1类型下拉? Anywho ...



要在SelectList上设置所选值,你需要做类似的事情。



Your not getting the selected value because your not setting any selected value. Also, your view is confusing, your looping over the drop down list in your view, you should be doing that in your model or controller (preferably model)....but not i guess its to show 1 type drop down per customer? Anywho...

To set the selected value on SelectList's you need to do something like this.

List<string> dropdown_content = new List<string>();
var query = from m2 in db.custtypes where m2.active == true orderby m2.name select m2.name;
SelectList list = new SelectList(query);

// This is where you find the selected item and if it isn't null, set Selected == true
var selectedItem = list.FirstOrDefault(m=>m.Value == id);

if(selectedItem != null)
{
   selectedItem.Selected = true;
}    

ViewBag.customertype = list;


这篇关于Asp.net MVC 3 - 来自具有selectedvalue的数据库的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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