我是Asp.net MVC和Razor的新手。我想使用Razor显示从DB到文本字段值的值。 我在控制器
中有以下代码public ActionResult edit(int id)
{
using (var context = new pmcontext())
{
var user_1 = from u in context.Users
where u.UserID==11
select u;
ViewBag.users = user_1.ToList();
return View();
}
}
在视图中我有
@model pm.Models.User
@{
ViewBag.Title = "edit";
}
<h2>Update User</h2>
@foreach (var user in ViewBag.Users)
{
<p><b> User Full Name: @user.fullname </b></p>
using (Html.BeginForm("Update", "Users", FormMethod.Post))
{
<div class="row">
<div class="col-sm-6 col-xs-6">Name </div>
<div class="col-sm-6 col-xs-6">@Html.TextBoxFor(model => model.fullname, new { Class = "form-control", value=user.fullname }) </div>
</div>
}
}
我还试图在文本框中显示user.fullname值,但未能这样做。
@Html.TextBoxFor(model => model.fullname, new { Class = "form-control", value="@user.fullname" })
答案 0 :(得分:0)
你的控制器应该是:
using (var context = new pmcontext())
{
//here how you can pass strongly typed model to View
ViewData.Model = context.Users.Where(x => x.UserID == 11).ToList();
return View();
}
然后在您的视图中更改您的模型:
@model IList<pm.Models.User> @*this is your actual model*@
@{
ViewBag.Title = "edit";
}
<h2>Update User</h2>
@foreach (var user in Model)
{
<p><b> User Full Name: @user.fullname </b></p>
using (Html.BeginForm("Update", "Users", FormMethod.Post))
{
<div class="row">
<div class="col-sm-6 col-xs-6">Name </div>
<div class="col-sm-6 col-xs-6">@Html.TextBoxFor(model => model.fullname, new { @class = "form-control"}) </div>
</div>
}
}
我更改了模型,在class
中转义htmlAttrubutes
并删除value=user.fullname
您不需要它,因为TextBoxFor
从您的模型属性中获取此值。< / p>
但请注意,通过这种方式,您将破坏绑定,并且不允许您以正确的方式POST
建模。
使一切正确的简单方法是使用for
循环而不是foreach
:
@for (int i = 0; i < Model.Count(); i++)
{
<p><b> User Full Name: @Model[i].fullname </b></p>
using (Html.BeginForm("Update", "Users", FormMethod.Post))
{
<div class="row">
<div class="col-sm-6 col-xs-6">Name </div>
<div class="col-sm-6 col-xs-6">@Html.TextBoxFor(model => Model[i].fullname, new { @class = "form-control"}) </div>
</div>
}
}
这将为您的name
生成正确的input
属性,并且绑定将在POST
上正常工作。
答案 1 :(得分:0)
在控制器中
public ActionResult edit(int id)
{
using (var context = new pmcontext())
{
List<User> user_1= context.Users.where(x=>x.UserID==1).ToList();
return View(user_1);
}
}
答案 2 :(得分:-1)
public ActionResult edit(int id) {
using (var context = new pmcontext())
{
var user_1 = (from u in context.Users
where u.UserID == 11
select u).ToList();
ViewBag.users = user_1;
//make your Model type class object
User model = new User();
model.fullname = user_1.fullname;
///Pass your Model type class object On View.
return View(model);
}
}