【问题标题】:Pass the values from View to Controller for Dynamically populated forms将值从视图传递到控制器以动态填充表单
【发布时间】:2017-06-02 06:18:26
【问题描述】:

我有一个表单,其中 TextBox 是动态填充的。用户可以灵活地添加删除文本框,这是使用 JQuery 完成的。 我需要在提交时将 TextBox 的 value 传递给我的 Controller

这是我的View

@using (Html.BeginForm("Controller", "Admin", FormMethod.Post, new { required = "required" }))
{
    <h4>Add new Q&A</h4>
    <div id='TextBoxesGroup'>
        <div id="TextBoxDiv1">
            <input type="text" name="Question" id="Question" required placeholder="Question 1" class="form-control" /><br />
        </div>
    </div>
            <input type="button" name="Add" id="Add" value="Add" class="btn btn-success" />
            <input type="button" name="Remove" id="Remove" value="Remove" class="btn btn-danger" /> <br /><br />
            <textarea rows="5" name="Answer" id="Answer" placeholder="Answer" required class="form-control"></textarea><br />
            @Html.DropDownList("Intent", ViewData["Intent"] as List<SelectListItem>, "Select Intent", new { @class = "form-control", required = "required" })
            <br /><input type="text" name="PrimaryEntity" id="PrimaryEntity" placeholder="Primary keyword" required class="form-control" /><br />
            <input type="text" name="SecondaryEntity" id="SecondaryEntity" placeholder="Secondary keyword (optional)" class="form-control" /><br />
            <input type="submit" name="Submit" id="Submit" class="btn btn-success" />
}

这就是我的 JS 的样子

  $(document).ready(function () {
    var counter = 2;
    $("#Add").click(function () {
        var newTextBoxDiv = $(document.createElement('div'))
             .attr("id", 'TextBoxDiv' + counter);
        newTextBoxDiv.after().html('<input type="text" name="textbox' + counter +
              '" id="Question' + counter + '" value="" class="form-control" required placeholder="Question ' + counter +
              '"> <br />');
        newTextBoxDiv.appendTo("#TextBoxesGroup");
        counter++;
    });

    $("#Remove").click(function () {
        if (counter == 2) {
            alert("No more textbox to remove");
            return false;
        }
        counter--;
        $("#TextBoxDiv" + counter).remove();
    });
});

对不起,如果我听起来很蹩脚。刚刚开始使用 MVC!

【问题讨论】:

  • 有什么问题?
  • 建议你研究答案herehere中的代码
  • @KateFernando 文本框是使用 Javascript 填充的,我想将这些文本框的值传递给控制器​​。我不知道这是否可以做到,如果我做对了?
  • @StephenMuecke是的,应该这样做。

标签: javascript c# jquery asp.net-mvc asp.net-mvc-4


【解决方案1】:

您可以创建具有List&lt;string&gt; 类型的属性Questions 和其他必需属性的简单模型。

然后从 jQuery 你可以使用一个简单的逻辑添加多个文本框:

<input type="text" name="Model.Questions[" + index + "]" id="Model_Questions_" + index />

渲染使用:

@for (int i = 0; i < Model.Questions.Count; i++)
{
    @Html.TextBoxFor(x => Model.Questions[i], { .... })
}

当您发布表单时,问题文本框中的所有值都将发布到模型的问题列表中。

注意:我没有在VS中写过上面的代码,所以可能会有一些错误你可以自己修复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多