在下面的例子中,如何将数据从IEnumerable数据从控制器传递到视图 [英] How to pass the data from IEnumerable data from controller to view in the case below
问题描述
问题描述:
我试图从控制器传递Ienumerable数据到视图来填充我的dropdownlist。虽然这样做我已经以某种方式成功获取数据直到控制器。我怎么通过它对视图有什么影响吗?我对剃须刀的语法有点不知情,因为它是ma rookie fr mvc。
任何帮助都会非常感激。
* note请原谅任何代码滥用。
谢谢。
型号:
Problem Description:
I a trying to pass the Ienumerable data from controller to view to populate my dropdownlist.While doing so i have somehow succeded to get the data till the controller.How do i pass it to the view?.I am a bit unaware about the razor syntax as m a rookie fr mvc.
Any help would be really appreciated.
*note Forgive any code abuses.
Thanks.
Model:
public class TS_entryscreen
{
public static string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection connfordata = new SqlConnection(connstr);
public string Name { get; set; }
public IEnumerable<string> fillalldrp()
{
DataTable dtfrfilluser = new DataTable();
connfordata.Open();
SqlCommand cmdfruser = new SqlCommand("select (s000_firstname+s000_lastname)as Name from s000_users", connfordata);
SqlDataAdapter dafruser = new SqlDataAdapter(cmdfruser);
connfordata.Close();
dafruser.Fill(dtfrfilluser);
List<string> lstusers = new List<string>();
lstusers = dtfrfilluser.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("Name")).ToList();
IEnumerable<string> myEnumerable = lstusers;
return myEnumerable;
}
控制器:
Controller:
public ActionResult Index()
{
TS_entryscreen tsuser = new TS_entryscreen();
IEnumerable<string> tsnewuser = tsuser.fillalldrp();
return View(tsnewuser);
}
查看:
View:
@model loginntimesheet.Models.TS_entryscreen
@ {
ViewBag.Title =主页;
}
@section特色{
@model loginntimesheet.Models.TS_entryscreen
@{
ViewBag.Title = "Home Page";
}
@section featured {
< ; hgroup class =title>
@ Html.DropDownList(名称);
<hgroup class="title">
@Html.DropDownList("Name");
}
}
推荐答案
你应该仔细阅读一本书或在线教程MVC,因为你不能通过在论坛上提问来从头学到东西。您的模型由您从控制器返回的内容定义
You should really go through a book or on-line tutorials for MVC as you can't learn something from scratch by asking questions on a forum. Your model is defined by what you return from the controller
return View(tsnewuser);
tsnewuser是IEnumerable< string>所以你的视图需要定义为模型,但是你要定义
tsnewuser is IEnumerable<string> so your view needs to define that as the model, but you are defining
@model loginntimesheet.Models.TS_entryscreen
所以需要
So that needs to be
@model IEnumerable<string>
您可以使用模型访问模型(模型是一个特殊变量,永远是@model中定义的类型),所以循环你的字符串
You access the model using "Model" (Model is a special variable that will always be the type defined in @model), so to loop through your strings
foreach (string name in Model)
{
<p>@name</p>
}
但是下拉列表包含一系列包含两个值,名称和值的内容,您还需要在某处存储所选项目,所以你不能从字符串列表中下拉。有一个特殊的结构用于制作下拉菜单,如果你看一下会有一些示例代码
http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with -asp-net-mvc.aspx [ ^ ]
这篇关于在下面的例子中,如何将数据从IEnumerable数据从控制器传递到视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!