我想将动态生成的文本框中的所有值从视图传递到控制器。
我的模特:
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");
}
我应该为此创建一个字符串列表吗?如果是,那怎么办? 请帮忙。
答案 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}}不为空。
相关问题:
答案 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();
}