我正在尝试在 texbox 中输入“UserId”,当我单击“Find User”按钮时,我需要根据 UserId 从数据库中获取“UserName”和“Role”并将它们显示在 texboxes 中,以便如果用户名和角色必须被编辑,它们将被编辑并更新到数据库。
但是,当我输入 UserId 时,模型中的 UserId 值可用,我可以查询数据库并获取结果并将它们分配给模型的用户名和角色(Model.UserName 和 Model.Role),但我是无法将它们绑定到 HTML.TextBoxFor。
我有一个像下面这样的模型
public class EditUserInfoModel
{
[Display(Name = "User ID")]
public string UserId { get; set; }
[Display(Name = "User Name")]
public string UserName { get; set; }
[Display(Name = "Role")]
[DataType(DataType.Text)]
public string Role { get; set; }
}
..和控制器如下
[HttpPost]
public ActionResult EditUserInfo(EditUserInfoModel model)
{
if (ModelState.IsValid)
{
string con = ConfigurationManager.ConnectionStrings["DMSCON"].ConnectionString;
DataTable dt = new DataTable();
SqlConnection dbCon = new SqlConnection(con);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select user_name,user_role from user_info where
user_id=@userid";
cmd.Parameters.Add(new SqlParameter("@userid", model.UserId));
cmd.Connection = dbCon;
dbCon.Open();
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(dt);
EditUserInfoModel myModel = new EditUserInfoModel();
foreach (DataRow row in dt.Rows)
{
myModel.UserName = row["user_name"].ToString();
myModel.Role = row["user_role"].ToString();
//model.isBlocked = (bool)row[""];
//model.isExpired = (bool)row[""];
// model.UserId = "somevalue";
}
return View("EditUserInfo", myModel);
}
return View();
}
和下面的视图
@model WebDMS.Models.EditUserInfoModel
@{
ViewBag.Title = "EditUserInfo";
//Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
<h2>
EditUserInfo</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>EditUserInfoModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.UserId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserId)
@Html.ValidationMessageFor(model => model.UserId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Role)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Role)
@Html.ValidationMessageFor(model => model.Role)
</div>
<input type="submit" value="Find User" />
</fieldset>
}