我想更新一些字段,但是要对模型的所有字段进行建模。因此,当它在post方法中检查 ModelState 时,由于所有字段都是必需的,因此返回false。因此,我如何使用此模型或任何其他方式更新两个字段。
模型
public class User
{
[Required(ErrorMessage ="The Name field is required")]
public string FullName { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Phone { get; set; }
[Required]
public string Password { get; set; }
}
查看
@using (Html.BeginForm("action", "controller", FormMethod.Post))
{
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">Your Name</label>
@Html.TextBoxFor(model => model.FullName, new { @class = "form-control", placeholder = "Your Name" })
@Html.ValidationMessageFor(model => model.FullName, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">User Name</label>
@Html.TextBoxFor(model => model.UserName, new { @class = "form-control", placeholder = "User Name" })
@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
</div>
</div>
</div>
}
控制器
public ActionResult Name(int id)
{
var SingleUserDetails = DB.Users.Where(x => x.id == id).FirstOrDefault();
return View(SingleUserDetails);
}
[HttpPost]
public ActionResult Name(User userobject)
{
if(ModelState.IsValid)
{
}
return View();
}
答案 0 :(得分:2)
您不应该在控制器的Post
方法中使用模型。您应该仅使用来自视图的字段来创建ViewModel
。
public class UserVM
{
public int Id {get; set; }
public string FullName { get; set; }
public string UserName { get; set; }
}
之后,您需要找到要更新的用户并应用新设置