Html.HiddenFor()实际做什么?

时间:2020-08-01 07:38:46

标签: asp.net asp.net-mvc html-helper

Html.HiddenFor()用于当我要在页面上保留字段但不希望用户注意到它时,例如Id字段等,但是它是否为Id字段初始化了一个值?如果Id字段已经有一个值,那么它将做什么?我目前正在使用ASP.Net MVC上一门课程,并且正在实现一个可以编辑和创建新客户的控制器。为此,我将viewModel传递给控制器​​,并检查此viewModel中的Customer对象是否具有不等于0的ID,如果它等于0,则这是我需要的新客户添加到我的数据库中,否则我需要对其进行编辑,因为它实际上存在于我的数据库中。那么在这种情况下,Html.HiddenFor()会做什么?如果我从视图中删除Html.HiddenFor()标记,则在编辑客户时(而不是对其进行编辑)它将创建一个新客户。这是为什么?我正在编辑的客户已经有一个ID,这是我数据库中的密钥,那么为什么在我的控制器中将他的ID视为0,那么Html.HiddenFor()的作用是什么?我以前见过有关HiddenFor的问题,并且已经阅读了文档,但仍然无法获得其实际功能,尤其是当确实存在一个字段的值不是0(Id字段)时

我的客户类别:

public class Customer
    {
        public int Id { get; set; }


        [Required] //means that it wont be nullable
        [StringLength(255)] //max len 255 instead of inf 
        public string Name { get; set; }


        public bool IsSubscribedToNewsletter { get; set; }


        [Display(Name = "Membership Type")]
        public MembershipType MembershipType { get; set; }  //navigation property, allows us to navigate from one type to another


        [Display(Name = "Membership Type")]

        public byte MembershipTypeId { get; set; } //foreign key of membership object for optimization purposes
        

        [Display(Name = "Date of Birth")]
        public DateTime? Birthdate { get; set; }  //nullable 
    }

CustomersController中的Save方法

 [HttpPost]  //make sure not httpget, if modify data, never let it be httpget
        public ActionResult Save(CustomerFormViewModel viewModel) //or use updatecustomerdto (small class we create with only properties we want to update
        {
            if (viewModel.Customer.Id == 0)
            {
                _context.Customers.Add(viewModel.Customer);
            }
            else
            {
                Customer customerInDb = _context.Customers.Single(c => c.Id == viewModel.Customer.Id); //customer object in db
                                                                                                       //need to update its properties to be like those in viemodelcustomer

                //TryUpdateModel(customerInDb,"",new string[] { "Name", "Id" }); //dont use this approach since security conecerns
                //name id is whitelisted as the only things to be updated
                //OR
                //Mapper.Map(customer, customerInDb)

                customerInDb.Name = viewModel.Customer.Name; 
                customerInDb.Birthdate = viewModel.Customer.Birthdate;
                customerInDb.MembershipTypeId = viewModel.Customer.MembershipTypeId;
                customerInDb.IsSubscribedToNewsletter = viewModel.Customer.IsSubscribedToNewsletter;

            }

            _context.SaveChanges(); //must save changes after creating a change in the database

            return RedirectToAction("Index", "Customers");
        }

我的CustomerFormView中Html.HiddenFor元素所在的位置位于最后一个元素之前的行中

@model VidlyProject.ViewModels.CustomerFormViewModel

@{
    ViewBag.Title = "New";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>New Customer</h2>

@using (Html.BeginForm("Save", "Customers"))
{
    <!--we surround it in using since beginform creates a <form> tag not </form> so we need to close it afterwards-->
    <div class="form-group">
        <!--bootstrap class for a responsive form-->
        @Html.LabelFor(m => m.Customer.Name) <!--label-->
        @Html.TextBoxFor(m => m.Customer.Name, new { @class = "form-control" }) <!--next paramter is an anonymous object, where each element is rendered as an html attribute-->
        @**\@class not class because class is reserved in c#-->**@
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Customer.Birthdate)
        @*OR <lable for="Birthdate">Date Of Birth</label>*@
                                                    @*format string to format the date *@
        @Html.TextBoxFor(m => m.Customer.Birthdate, "{0: d MMM yyyy}", new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Customer.MembershipTypeId)
        @Html.DropDownListFor(m => m.Customer.MembershipTypeId, 
                              new SelectList(Model.MembershipTypes, @*initialize a drop down list*@
                              "Id", @*Name of property in membershiptype class that holds the value for each item*@
                              "Name"), @*Property that holds the text of each item*@
                              "Please select a membership type", @*message at the beginning of the dropdown*@
                              new { @class = "form-control"})
    </div>

    <div class="checkbox">
        <label>
            @Html.CheckBoxFor(m => m.Customer.IsSubscribedToNewsletter, new { @class = "form-check-input" }) Subscribed to the Newsletter?
        </label>
    </div>
    @Html.HiddenFor(c => c.Customer.Id) <!--so that we set an id and the id isnt zero-->
    <button type="submit" class="btn btn-primary">Save</button>
    
}

1 个答案:

答案 0 :(得分:1)

让我们在这里学习一点算法
假设您是酒店的接待员,并且您的职责是向酒店内外的客人举报。现在在您的酒店,每当有顾客进来时,您都需要他的注册卡。如果客户没有,那您​​肯定知道这是他的新时机。在这种情况下,您必须将他注册为新用户。如果他已经有了,那么您将打开他的记录并记入时间,然后再超时。
现在,一位客户声称他已经注册。您搜索了记录,但他出示的卡是另一张发给另一客户的假冒产品,甚至更糟的是,该卡上的ID不在您的记录中。除了为该用户执行新注册外,您别无选择。

这里的问题是,用户未出示身份证或身份证是假的。如果您不输入Html.LabelFor,那么将没有字段可保存先前发布给用户的ID

相关问题