我不太明白这是如何工作的。
从我的实体对象传递参数工作正常。但是当我创建新字段时,只检索到第一个字段。
模型用户类:
public class User {
[Key]
public long Uid { get; set; }
[Required]
[StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email:")]
public string Email { get; set; }
[Required]
[StringLength(20, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
[Display(Name = "User Name:")]
public string Username { get; set; }
public string Password { get; set; }
public byte Role { get; set; }
public DateTime Created { get; set; }
}
CSHTML:
@using (Html.BeginForm( null,
null,
FormMethod.Post,
new { id = "regform" })
) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Register</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Username)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Username)
@Html.ValidationMessageFor(model => model.Username)
</div>
<div class="editor-label">
Password:
</div>
<div class="editor-field">
@Html.Password("pwd")
</div>
<div class="editor-label">
Confirm Password:
</div>
<div class="editor-field">
@Html.Password("confirm")
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
}
控制器:
[HttpPost]
public ActionResult Register(User user, string pwd, string confirm) {
user.Username = confirm;
user.Created = DateTime.Now;
user.Role = 255;
user.Password = EncryptPassword.Password(pwd);
if (ModelState.IsValid && pwd == confirm) {
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
我感到困惑的地方是pwd
很好。confirm
另一方面依然存在null
。我最初的想法是它是按顺序调用的,confirm
在模型中是简单的conPwd
。当这不起作用时,我将其名称更改为confirm
. 它仍然无法正常工作,我找不到任何解释如何将多个参数传递给控制器的东西。
编辑:更新了我的代码。信不信由你,仅此一项就花费了我一天的大部分时间来写作,因为我一直在努力了解自己在做什么。当您同时学习 Entities、LINQ、MVC、ASP.NET 和 Razor 时,有很多东西需要学习。基本 C# 是我了解这一点的唯一部分。:)