我整天都在挣扎 这是我有史以来的第一篇文章,如果很难理解或格式不正确,敬请见谅
我正在使用ViewModel在一个视图中合并两个实体。对于第一个实体,我使用textboxfor和lablefor html帮助器来收集发布请求的数据。 对于第二实体Im,使用下拉列表,该下拉列表是在另一视图中输入的一组地址对象的选择列表。 我在地址类上使用了数据注释,以使所有字段必填。 一旦条目通过验证并通过添加地址视图保存到我的数据库中。当我尝试使用视图模型选择它时,我收到验证异常,该异常指示我的地址条目中必填字段
如果我删除了对地址类的验证,那似乎可行
我的控制器
public ActionResult AddMember()
{
var ViewMember = new MemberViewModel();
ViewMember.AddressList = new SelectList(_context.Addresses, "Id", "streetName");
return View(ViewMember);
}
[HttpPost]
public ActionResult AddMember(MemberViewModel Entry)
{
var entry = new Member();
entry = Entry.member;
entry.Address = new Address() {Id= Entry.addressId };
if (ModelState.IsValid)
{
repository.AddMember(entry, _context);
TempData["message"] = "Your Member was added";
return RedirectToAction("Members", new { id = entry.Id });
}
return View();
}
我的观点
@model AdesinaWebApp.ViewModels.MemberViewModel
@{
ViewBag.Title = "AddMember";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AddMember</h2>
@using (Html.BeginForm()){
@Html.LabelFor(fn => fn.member.Name)<br>
@Html.TextBoxFor(fn => fn.member.Name)<br /><br />
@Html.LabelFor(fn => fn.member.LastName)<br>
@Html.TextBoxFor(fn => fn.member.LastName)<br />
@*@Html.LabelFor(fn => fn.address.DoorNumber)<br>
@Html.TextBoxFor(fn => fn.address.DoorNumber)<br /><br />
@Html.LabelFor(fn => fn.address.streetName)<br>
@Html.TextBoxFor(fn => fn.address.streetName)<br /><br />
@Html.LabelFor(fn => fn.address.PostCode)<br>
@Html.TextBoxFor(fn => fn.address.PostCode)<br /><br />*@
@Html.LabelFor(m=>m.addressId)
@Html.DropDownListFor(m=>m.addressId,Model.AddressList,"please select your address")
<button type="submit">Submit</button>
}
我的视图模型
public class MemberViewModel
{
public int addressId { get; set; }
public Address address { get; set; }
public Member member { get; set; } = new Member();
public SelectList AddressList { get; set; }
}
我的地址分类
public class Address
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a Door Number")]
public int DoorNumber { get; set; }
[Required(ErrorMessage = "Please enter a Street Name.")]
public string streetName { get; set; }
[Required(ErrorMessage = "Please enter a Post Code.")]
public string PostCode { get; set; }
public ICollection<Member> Members { get; set; }
}
public class Member
{
[Key]
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string LastName { get; set; }
public Address Address { get; set; }
}
非常感谢您的帮助