如何将动态创建的文本框值从视图传递到MVC中的控制器

时间:2019-02-14 04:07:41

标签: c# html asp.net-mvc

我想将动态生成的文本框中的所有值从视图传递到控制器。

我的模特:

public class QuestionModel
{
    [Required(ErrorMessage = "{0} is required")]
    [Display(Name = "Question here")]
    public string Question { get; set; }
}

我的观点:

@using (Html.BeginForm("Add_Question", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
        {
            <div class="form-group">
                    //here I'm generating dynamic textboxes
                    @for (int i = 1; i <= numberOfQuestions; i++)
                    {
                        <div class="col-md-12">
                            @Html.LabelFor(model => model.Question, new {  })
                            @Html.TextBoxFor(model => model.Question, "", new { @required = "required", @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.Question, "", new { @class = "text-danger" })
                        </div>
                    }
                </div>

                <div class="form-group">
                    <div class="col-md-12">
                        <input type="submit" value="Done" class="btn-success form-control" />
                    </div>
                </div>
        }

我的控制器:

public ActionResult Add_Question()
    {
         return View();
    }

    [HttpPost]
    public ActionResult Add_Question(QuestionModel model)
    {
        //Get all textbox values here
        return RedirectToAction("Home", "Home");
    }

我应该为此创建一个字符串列表吗?如果是,那怎么办? 请帮忙。

3 个答案:

答案 0 :(得分:1)

您可以稍微修改viewmodel属性并在视图内循环以包含List<string>中的每个元素,如下所示:

模型

[Display(Name = "Question here")]
public List<string> Question { get; set; }

查看

@for (int i = 0; i < numberOfQuestions; i++)
{
    <div class="col-md-12">
    @Html.LabelFor(model => model.Question)
    @Html.TextBoxFor(model => model.Question[i], "", new { @required = "required", @class = "form-control" })
    </div>
}

请注意,集合索引从零开始,因此第一个问题的索引应为0。

附加说明:

您可能需要按照this reference的要求为List<string>创建自定义验证属性,因为默认的RequiredAttribute仅检查整个集合项的null而不是总数({{ 1}}不为空。

相关问题:

Asp.net razor textbox array for list items

答案 1 :(得分:0)

使用模型返回视图:

[HttpPost]
public ActionResult Add_Question(QuestionModel model)
{
    return View(model);
}

答案 2 :(得分:0)

you can retrieve the values using the Formcollection object, but your dynamically created text boxes should have unique id for eg:- Question1, Question2 etc.

And then you can loop through Formcollection object.

below code is just for single textbox you need to create loop and retrieve

public ActionResult AddQuestion(FormCollection form)
        {
            string question1 = form["Question1"].ToString();           
            return View();
        }