【问题标题】:Passing a model to view and losing property values on HttpPost传递模型以查看和丢失 HttpPost 上的属性值
【发布时间】:2015-08-24 03:55:40
【问题描述】:

我是 MVC 的新手,我猜这个问题反映了这一点。

我有 2 个 ActionResults - 注册 - 一个在 HttpGet,另一个在 HttpPost。在HttpGet 上,我创建了一个模型实例,根据查询字符串值设置公司属性并将模型传递给视图。到目前为止,一切顺利。

HttpPost 发生时,公司属性设置为空。好像什么都没有设置。我究竟做错了什么?

注册 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; }
    }
}

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    RegisterModel 中添加一个属性来保存固定ID,并将此ID 传递到您的视图并通过隐藏输入回发ID。

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

    在您的视图中,在表单元素中添加一个隐藏字段:

    @Html.HiddenFor(model=>model.FirmID);
    

    在回发操作中,您可以使用 id 来获取您的对象

    [HttpPost]
    public ActionResult Register(RegisterModel model)
    {
        // other codes
    
        // your firm id is here you could do whatever you want
        var firmID=model.FirmID;
    
    }
    

    【讨论】:

    • 谢谢!这行得通。我不知道我必须添加一个隐藏字段,以为 MVC 会知道它们。非常感谢所有。
    • 如果我的属性类型比原始类型更复杂怎么办?我需要为每个属性创建一个隐藏输入吗?
    【解决方案2】:

    在注册视图中没有设置您的公司属性的输入字段,因此它返回为空

    【讨论】:

    • 如果我不想显示这些字段,而我只是传递这些字段,因为我想在 HTTPPost 上对它们做些什么呢?我应该检查 HTTPPost 中的查询字符串并在 HTTPGet 中执行我的逻辑吗?
    • @user1203996,在这种情况下,您使用隐藏字段:您需要使用 HiddenFor() 而不是 TextBoxFor()。在 MVC 中,您希望通过 POST 或 GET 传递给服务器的所有内容都需要在输入中:文本框、文本区域、隐藏、选择等。
    • 就像 Romias ans gardarvalur 所说的那样使用 HiddenFor()
    猜你喜欢
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2015-06-21
    • 2011-06-03
    • 2020-08-03
    • 2016-01-01
    相关资源
    最近更新 更多