gpt4 book ai didi

asp.net-mvc - 创建 View 正在发布空对象

转载 作者:行者123 更新时间:2023-12-04 22:01:20 24 4
gpt4 key购买 nike

应该是一个容易回答的问题。
我正在尝试在 View 中创建一个对象。包含对象的类由一个 User 类和一个密码组成。
当我点击提交按钮时, Controller 为密码和用户选择空值。
见下面的容器类、 Controller 和 View ;

public class UserExtended
{
public UserITOC User { get; set; }
public string Password { get; set; }
}

[Authorize]
public ActionResult Create()
{
return View(new UserExtended());
}

//
// POST: /Dinners/Create

[Authorize(Roles = "Administrator")]
[HttpPost]
public ActionResult Create(UserExtended user)
{
if (ModelState.IsValid)
{
// Create user in the User datatable
SqlUsersRepository sqlRepository = new SqlUsersRepository();
ITOCEntities db = new ITOCEntities();
db.UserITOCs.AddObject(user.User);

// Create user as an authenticated user within the Reader role.
int i = user.User.EmailAddress.IndexOf('@') - 1;
string userName = user.User.EmailAddress.Substring(0, i);
string email = user.User.EmailAddress;
Membership.CreateUser(userName, user.Password, email);
Roles.AddUserToRole(userName, "Reader"); // Automatically assigned as a Reader
}
return View(new UserExtended());
}

“%>

创造

<h2>Create</h2>

<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>

<fieldset>
<legend>Fields</legend>

<div class="editor-label">
<%: Html.LabelFor(model => model.User.Forename) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.User.Forename)%>
<%: Html.ValidationMessageFor(model => model.User.Forename)%>
</div>

<div class="editor-label">
<%: Html.LabelFor(model => model.User.Surname) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.User.Surname)%>
<%: Html.ValidationMessageFor(model => model.User.Surname)%>
</div>

<div class="editor-label">
<%: Html.LabelFor(model => model.User.EmailAddress) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.User.EmailAddress)%>
<%: Html.ValidationMessageFor(model => model.User.EmailAddress)%>
</div>

<div class="editor-label">
<%: Html.LabelFor(model => model.Password) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Password)%>
<%: Html.ValidationMessageFor(model => model.Password) %>
</div>

<p>
<input type="submit" value="Create" />
</p>
</fieldset>

<% } %>

<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>

最佳答案

极其简单的解决方案:

更改您的操作签名

public ActionResult Create(UserExtended user)


public ActionResult Create(UserExtended UserExtended)

这样,ModelBinder将知道如何从Request中重新组装对象。

希望这可以帮助!

关于asp.net-mvc - 创建 View 正在发布空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3447672/

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