【问题标题】:.Net MVC add text box dynamically and bind to model.Net MVC 动态添加文本框并绑定到模型
【发布时间】:2020-09-18 11:35:25
【问题描述】:

我想动态添加文本框并将其绑定到我的模型,所以当我发布所有数据时都应该在 HttpPost 中。这是我的模型

 public class JobViewModel
    {
        public JobViewModel()
        {
            JobDescriptions = new List<JobDescription>();
        }
        public int Id { get; set; }
        [Required]
        public string JobTitle { get; set; }
        public List<JobDescription> JobDescriptions { get; set; }
}

这是我的 Razor 视图

@using (Html.BeginForm("CreateJob", "Jobs", FormMethod.Post, new { @id = "jobFrm" }))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
    <h4>Job</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.JobTitle, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.JobTitle, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.JobTitle, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.Label("Add Description", htmlAttributes: new { @class = "control-label col-md-2" })
       


 <div class="col-md-2">
            <input id="btnAdd" type="button" class="btn btn-success" value="Add"  />
        </div>

 ............. more fields and submit button ............

我搜索并尝试了不同的代码,他们在单击添加按钮时添加了文本框,但填充的文本框值未绑定到我的模型。有时它会添加空模型,或者根本不添加。 需要帮助将值绑定到我的模型

【问题讨论】:

    标签: .net asp.net-mvc asp.net-core


    【解决方案1】:

    您可以根据需要选择两种解决方案之一:

    • 如果您在渲染时从 Razor 添加动态控件,则使用条件添加控件。
    • 如果您想在运行时执行此操作,因此在浏览器中通过 javascript 使用正确的名称和 id 字段来创建和映射回来。

    【讨论】:

      【解决方案2】:

      我在尝试为一对多关系创建具有动态添加/删除功能的表单时引用了this。要记住的一件主要事情是确保新添加项目的索引。同样如上所述,将有一些客户端调用来为每个特定项目添加一个新的编辑器。 This post 还为我在设置编辑器模板时提供了一些很好的参考,客户端调用“AddNewItem”到表单并确保新添加项目的索引在必要时可用于删除。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-24
        • 1970-01-01
        • 2016-11-04
        • 1970-01-01
        • 2019-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多