我是MVC的新手,我猜这个问题反映了它。
我有2个ActionResults - 注册 - 一个HttpGet
另一个HttpPost
。在HttpGet
上,我创建了模型的实例,根据查询字符串值设置公司属性,并将模型传递给视图。到目前为止,非常好。
当HttpPost
发生时,公司属性设置为null。好像没有设置任何东西。我究竟做错了什么?
注册HTTPGet
[AllowAnonymous]
public ActionResult Register(Guid Firm)
{
InnuendoContext DB = new InnuendoContext();
RegisterModel RM = new RegisterModel();
RM.Firm = (from F in DB.Firms
where F.FirmId == Firm
select F).FirstOrDefault();
return View(RM);
}
注册HTTPPost
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register( RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, propertyValues: new
{
Name = model.Name,
Surname = model.Surname,
Firm_FirmID = model.Firm
});
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
}
查看
@model Innuendo.Models.RegisterModel
@{
ViewBag.Title = "Register";
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>Create a new account.</h2>
</hgroup>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
</li>
<li>
@Html.LabelFor(m => m.Surname)
@Html.TextBoxFor(m => m.Surname)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
模型
namespace Innuendo.Models
{
[Table("Firms")]
public class FirmModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Guid FirmId { get; set; }
[Display(Name = "Firm Name")]
[Required]
[StringLength(250)]
public string Name { get; set; }
[Required]
public virtual AddressModel Address { get; set; }
[StringLength(250)]
public string LogoPath { get; set; }
}
}
答案 0 :(得分:1)
在PlayKeys.externalizeResources := false
中添加一个属性以保存公司ID,并将此ID传递给您的视图,并使用隐藏的输入回发ID。
RegisterModel
在你采取行动:
public RegisterModel
{
// other codes
public Guid FirmID {get;set;}
}
在您的视图中,在表单元素中添加一个隐藏字段:
public ActionResult Register(Guid Firm)
{
// other codes
// also don't fetch firm object if you don't want to show firm data to user
RM.FirmID=Firm;
View(RM);
}
在回发操作中,您可以使用id来获取对象
@Html.HiddenFor(model=>model.FirmID);