【问题标题】:How to auto fill fields in a form using @Html.EditorFor in ASP.net MVC 5?如何在 ASP.net MVC 5 中使用 @Html.EditorFor 自动填充表单中的字段?
【发布时间】:2017-02-04 20:18:24
【问题描述】:

我正在使用 Visual Studio for asp.net mvc 5 的自动生成表单,它将信息保存到数据库中。它是带有实体框架的 asp.net 标准脚手架等的创建视图。

我喜欢表单的外观,但我需要一个字段(创建日期)至少可以自动填充(但最好是自动填充和隐藏)。问题是我根本不理解自动生成的代码,而且我查找它的努力没有成功。我也没有努力去理解它。我仍然是 html 助手的初学者,我认为这些是。

这是我正在使用的表单元素。中间的部分是我需要更改为自动填充的部分(创建日期字段),我认为相关部分正在更改 EditorFor。但我不知道:

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()


            <div class="form-horizontal">
                <h4>New Patient:</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

... //为简单起见删除了其他表单项

    <div class="form-group">
        @Html.LabelFor(model => model.DateCreated,"Date Created", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DateCreated, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DateCreated, "", new { @class = "text-danger" })
        </div>
    </div>

... //为简单起见,省略了更多项目

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
}

这部分自动生成的控制器如下所示:

// GET: Subjects/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Subjects/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Name,DOB,Male,Female,Address,City,ZIP,PhoneHome,PhoneCell,Email,EmergencyContact,EmergencyContactPhone,EmergencyContactRelationship,ReferredBy,DateCreated,Allergy,AllergyDescription,HighBloodPressure,LowBloodPressure,HeartCondition,Diabetes,Anemia,HighCholesterol,Pacemaker,Epilepsy,Pregnant,Cancer,STD,Pain,PainDescription,Headache,HeadacheDescription,CommonCold,HighBloodPressureConcern,Stress,Depression,Sleep,Menstruation,Fertility,WeightControl,Other")] Subject subject)
    {
        if (ModelState.IsValid)
        {
            db.SubjectDatabase.Add(subject);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(subject);
    }

如果您不知道如何自动填充和/或隐藏表单元素 datecreated,请您指出我可以自己学习解决这个问题的地方。我觉得我编程很通情达理,只是对html helpers 或者controller 中的bind 函数不太了解。

【问题讨论】:

  • DateCreated 字段绝不应采用用于创建数据的形式。在将对象保存到数据库之前立即在 POST 方法中设置该值。并且不要在你的视图中使用数据模型——创建一个视图模型——参考What is ViewModel in MVC?
  • 没错,只需删除包含@Html.EditorFor(model =&gt; model.DateCreated 的整个&lt;div class="form-group"&gt;,然后在您的操作中执行此操作,如下所示:model.DateCreated = DateTime.Now
  • 好的。感谢您澄清如何执行此操作。我很困惑,因为这就像两件我不太了解的东西相互影响,我不想破坏一些东西。我将在方法中添加分配。谢谢

标签: c# html asp.net asp.net-mvc


【解决方案1】:

从您的视图中删除此部分

 <div class="form-group">
        @Html.LabelFor(model => model.DateCreated,"Date Created", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DateCreated, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DateCreated, "", new { @class = "text-danger" })
        </div>
    </div>

然后,在您的 Controller 中,从 Bind 属性中删除 DateCreated 并分配 DateCreated 属性:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Name,DOB,Male,Female,Address,City,ZIP,PhoneHome,PhoneCell,Email,EmergencyContact,EmergencyContactPhone,EmergencyContactRelationship,ReferredBy,Allergy,AllergyDescription,HighBloodPressure,LowBloodPressure,HeartCondition,Diabetes,Anemia,HighCholesterol,Pacemaker,Epilepsy,Pregnant,Cancer,STD,Pain,PainDescription,Headache,HeadacheDescription,CommonCold,HighBloodPressureConcern,Stress,Depression,Sleep,Menstruation,Fertility,WeightControl,Other")] Subject subject)
    {
        if (ModelState.IsValid)
        {
            subject.DateCreated = DateTime.Now; //if you want UTC time, use DateTime.UtcNow
            db.SubjectDatabase.Add(subject);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(subject);
    }

【讨论】:

    【解决方案2】:

    @Value也可以通过@Html.EditorFor来预填充:

    例子:

    @Html.EditorFor(c => c.Propertyname, new { @Value = "5" })
    

    可以在以下位置找到更多信息: Html.EditorFor Set Default Value

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      相关资源
      最近更新 更多