【发布时间】:2015-12-06 00:05:45
【问题描述】:
将模型与一类中的两个表绑定时遇到问题。将表单发布到控制器时,表单未将值绑定到模型。
型号:
public class BasicProfileModel {
public BasicProfileModel() {
this.user = new User();
this.basicProfile = new BasicProfile();
}
public User user { get; set; }
public BasicProfile basicProfile { get; set; }
}
User 和 Basic Profile 类是两个具有以下属性的表:
public class User {
public string UserId { get; set; }//not null and PK
public string EmailId { get; set; }//no null
public string Salt { get; set; }//not null
public string Password { get; set; }//not null
public string Role { get; set; }//not null
public bool HasCompleteProfile { get; set; }//not null
}
public class BasicProfile {
public string UserId { get; set; }//not null FK
public string FirstName { get; set; }//not null
public string LastName { get; set; }
public string Gender { get; set; }//not null
public int YearOfBirth { get; set; }//not null
public bool IsApprovedByUser { get; set; }//not null
public bool IsApprovedByAdmin { get; set; }//not null
public bool IsActiveByUser { get; set; }//not null
public bool isActiveByAdmin { get; set; }//not null
}
当我加载视图模型时,会显示在控制器(生成视图)或视图 c# 代码部分顶部初始化的任何值。 但是当我发布表单时,控制器显示的模型根本没有任何价值。 当我为单个表创建控制器/视图时,一切正常。这是控制器操作方法和视图的代码。
public ActionResult BasicRegister() {
BasicProfileModel model = new BasicProfileModel();
//any value initialised in model here displays in view elements e.g. text boxes.
return View("BasicRegister", model);
}
[HttpPost]
public ActionResult DoBasicRegister(BasicProfileModel basicProfile) {
return View("BasicRegister", basicProfile);
}
//这是视图
@model BasicProfileModel
@using (Html.BeginRouteForm("DoBasicRegister", FormMethod.Post)) {
<div>
@Html.TextBoxFor(m => m.user.EmailId)
</div>
<div>
@Html.TextBoxFor(m => m.user.Password)
</div>
<div>
@Html.TextBoxFor(m => m.basicProfile.FirstName)
</div>
<div>
@Html.TextBoxFor(m => m.basicProfile.LastName)
</div>
<div>
<input type="submit" value="send" />
</div>
}
//路线
routes.MapRoute(
name: "BasicRegister",
url: "join",
defaults: new { controller = "Home", action = "BasicRegister" }
);
routes.MapRoute(
name: "DoBasicRegister",
url: "dojoin",
defaults: new { controller = "Home", action = "DoBasicRegister" }
);
【问题讨论】:
-
User 和 BasicProfile 是如何关联的?似乎您缺少一对一的关系。
-
User 的 UserId 为 PK,BasicProfile 的 UserId 为 FK。一对一的关系。使用 Linq 到 sql。
-
我想我只是对 BasicProfile 中没有公共用户用户 {get;set;} 的事实感到困惑。我不是说它应该是那样的。但我就是这样做的。 :) 我想如果你也想在类中显示关系。
-
我在删除数据库中的关系后尝试过,但仍然不起作用。
标签: c# asp.net-mvc asp.net-mvc-4 razor