无法将模型对象绑定到TextBoxFor

时间:2013-11-11 09:32:00

标签: asp.net-mvc-3

我正在尝试在texbox中输入'UserId',当我点击'查找用户'按钮时,我需要根据UserId从数据库中获取'UserName'和'Role'并将它们显示在texbox中,以便如果必须编辑用户名和角色,则将对其进行编辑并更新为数据库。

但是,当我输入UserId时,ModelId中的UserId值可用,我可以查询数据库并获取结果并将它们分配给Model的UserName和Role(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>
}

1 个答案:

答案 0 :(得分:0)

您需要在控制器操作方法和视图模型中进行一些修改。

<强>模型

public class EditUserInfoModel
{
    [Required]
    [Display(Name = "User ID")]
    public string UserId { get; set; }

    [Required]
    [Display(Name = "User Name")]
    public string UserName { get; set; }

    [Required]
    [Display(Name = "Role")]
    [DataType(DataType.Text)]
    public string Role { get; set; }
}

<强>控制器:

[HttpPost]
public ActionResult EditUserInfo(EditUserInfoModel model)
{
    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();
    }

    //return View("EditUserInfo", myModel);    //try removing this line
     return View(myModel);      
}

如果您使用dataannotations,则无需在操作方法中查看ModelState.IsValid。您视图中的表单字段上的@ValidationMessage将具有更多含义,并且将按预期工作

您无需显式调用视图名称。让MVC-3来处理。而是按照此回复中的提及进行尝试。

这些不是我会说管理和结构化的方法。始终Close()Dispose()您的Db连接,方法是将它们放在using()块或try-catch-finally块中。创建分层结构,以便将数据库交互与控制器操作分开。希望它有所帮助。