我的mvc控制器中有一个字典并存储了值,所以我想用视图显示这些值。
我的代码
public List<Dictionary<string, string>> getalllocation()
{
var locs = new List<Dictionary<string, string>>();
try
{
DataTable dt1 = new DataTable();
string connString = cnst.cnstrin();
string query = "SELECT * FROM `Mytable`.`location`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(dt1);
foreach (DataRow drow in dt1.Rows)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("id", drow["LocationId"].ToString());
dictionary.Add("name", drow["LocationName"].ToString());
locs.Add(dictionary);
}
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
return locs;
}
我的观点
@{
List<Dictionary<string,string>>locations=((HomeController)this.ViewContext.Controller).getalllocation();
}
<select name="select_item" id="select-sort" class="select__sort" tabindex="0">
@for (int i=0;i<locations.Count;i++)
{
if((i==0)&&(ViewBag.location==null))
{ }
}
<option value="1" selected='selected'>@locations</option>//I need to display here
</select>
现在我无法显示值,但数据位于location.Any idea?
答案 0 :(得分:0)
您可以实施以下帮助:
<select name="select_item" id="select-sort" class="select__sort" tabindex="0">
@GenerateSelect(locations)
</select>
然后使用它:
public class Location
{
public int Id { get; set; }
public string Name { get; set; }
}
然而,正如其他人已经提到的那样,使用带有预定义键的词典是一种非常糟糕的方法。
您可以创建一个新类:
List<Location>
生成public List<Location> GetAllocation()
{
try
{
DataTable dt1 = new DataTable();
string connString = cnst.cnstrin();
string query = "SELECT * FROM `Mytable`.`location`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(dt1);
return dt1.AsEnumerable().Select(row => new Location {
Id = row["LocationId"],
Name = row["LocationName"]
});
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
:
select
将其传递给您的模型视图,并生成@model List<Location>
<select name="select_item" id="select-sort" class="select__sort" tabindex="0">
@foreach (var loc in Model)
{
<option value="@loc.Id">@loc.Name</option>
}
</select>
:
$login=$this->Login_set->set_pass();
if(count($login) > 0){
$this->load->view('App_stay/pages/profile');
}else{
$this->load->view('App_stay/App_stay_login');
}