gpt4 book ai didi

c# - 在模型中绑定(bind)两个表 - ASP.NET MVC Razor

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:18 25 4
gpt4 key购买 nike

我在将模型与一个类中的两个表绑定(bind)时遇到问题。表单在将其发布到 Controller 时未将值绑定(bind)到模型。

型号:

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
}

当我加载 View 模型时,会显示在 Controller (生成 View )或 View C# 代码部分顶部初始化的任何值。但是当我发布表单时, Controller 显示的模型根本没有任何值(value)。当我为单个表创建 Controller / View 时,一切正常。这是 Controller 操作方法和 View 的代码。

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);
}

//这是 View

@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" }
);

最佳答案

您的模型是 null,因为您的模型有一个名为 basicProfile 的属性,并且您的 POST 方法有一个同名的参数。

将方法中参数的名称改为(say)

[HttpPost]
public ActionResult DoBasicRegister(BasicProfileModel model) {

模型将被正确绑定(bind)。

旁注:由于您的 View 仅包含数据模型的一些属性,因此正确的方法是使用仅包含您在 View 中显示/编辑的那些属性的 View 模型。

关于c# - 在模型中绑定(bind)两个表 - ASP.NET MVC Razor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com