您现在的位置是:网站首页> 编程资料编程资料

ASP.NET MVC前台动态添加文本框并在后台使用FormCollection接收值_实用技巧_

2023-05-24 317人已围观

简介 ASP.NET MVC前台动态添加文本框并在后台使用FormCollection接收值_实用技巧_

在"MVC批量添加,增加一条记录的同时添加N条集合属性所对应的个体"中,对于前台传来的多个TextBox值,在控制器方法中通过强类型来接收。使用FormCollection也可以接收来自前台的多个TextBox值。实现效果如下:

动态添加TextBox:

后台使用FormCollection接收来自前台的TextBox值,再以TempData把接收到的值返回:

当页面没有TextBox,点击"移除",提示"没有文本框可被移除":

在HomeController中,先获取前台用来计数的隐藏域的值,然后遍历,根据前台Input的name属性值的命名规则获取到每个TextBox的值。

 public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(FormCollection collection) { var inputCount = 0; //前端文本框的数量 var inputValues = new List();//前端文本款的值放到这个集合 if (int.TryParse(collection["TextBoxCount"], out inputCount)) { for (int i = 1; i <= inputCount; i++) { if (!string.IsNullOrEmpty(collection["textbox" + i])) { inputValues.Add(collection["textbox" + i]); } } } TempData["InputResult"] = inputValues; return View(); } }

在Home/Index.cshtml中,通过jquery添加或移除TextBox。

@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } 
@if (TempData["InputResult"] != null) {
    @foreach (var item in (List) TempData["InputResult"]) {
  • @item
  • }
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post)) {

@Html.Hidden("TextBoxCount", 1)
} @section scripts { }

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

-六神源码网