c# - 将 IEnumerable 传递给视图以生成表单,然后将表单数据传递回控制器
问题描述
我正在为我的办公室做一个项目。我正在寻找的最终结果是从数据库中提取样板字母,提取需要特定输入的部分,从这些部分生成表单,然后表单返回用户数据,并使用重建字母用户数据集成到信件的文本中。
例如,从数据库中提取的字符串如下所示
Claim #: |string^clmNum^Claim Number: | - Ref#: |string^RefNum^Reference Number: |
并在使用用户数据重建后最终如下所示:
Claim #: 123456 - Ref#: 789012
这就是我到目前为止所做的工作......
|之间的部分 被拉出、拆分并加载到 IEnumerable 中
我的 foo 模型是:
public class Foo
{
public string InputType {get; set;}
public string InputName {get; set;}
public string InputLabel {get; set;}
}
我使用 ViewModel 将 IEnumerable 传递给视图
public class FormBuildViewModel
{
public IEnumerable<Foo> FooProperty {get; set;}
}
然后,我在视图上使用以下 Razor 标记动态显示输入项。
<form>
@{ var e = Model.FooProperty.ToList();
foreach (var subItem in e)
{
<div class="FormGroup-items">
<label>@subItem.InputLabel</label>
<input name="@subItem.ObjName" type="text" />
</div>
}
}
<..// form button stuff //..>
</form>
这将创建以下 HTML:
<form>
<div class="FormGroup-items">
<label>Claim Number: </label>
<input name="clmNum" type="text" />
</div>
<div class="FormGroup-items">
<label>Reference Number: </label>
<input name="RefNum" type="text" />
</div>
<..// button stuff //..>
</form>
到目前为止,我已经完成了所有工作。我需要获取在动态创建的表单上输入的数据,并以我可以索引的方式将其返回到控制器以重建字符串。
我试过使用类似于这个的@html.beginform
@using (Html.BeginForm())
{
@for(int i=0; i<Model.Count; i++)
{
@Html.CheckBoxFor(m => m[i].IsActive, new { @value = Model[i].Id })
@Html.DisplayFor(m => m[i].Name)
}
<input type="submit" value="Save" />
}
但是要使用@Html.BeginForm,您需要在运行前知道项目的名称,而且它似乎不适用于像这样动态创建的表单。
我唯一能想到的是我需要将表单数据加载到 List<T> 并将其返回给控制器,但我想不出一种方法让 C# 允许我初始化 List<T>并加载视图中的值。我知道我一定会错过一些东西,但我现在有点迷失了。任何帮助,将不胜感激。
解决方案
您是否将视图模型传递回您的页面?这似乎您正在使用至少来自 5000 英尺视图的数据设置视图模型:
[HttpGet]
public IActionResult MyCallMethod()
{
FooProperty = getmydatafromsomewhere();
return View();
}
然后您的页面将有一种适当构建的方法
@model My.Name.Space.MyViewModel
@using (Html.BeginForm("Action", "Controller"))
{
@foreach (var item in @Model.FooProperty)
{
<div class="FormGroup-items">
<label asp-for="item.InputType" />
<input asp-for="item.InputType" class="form-control" />
</div>
//other data
}
}
我还假设您在控制器上进行了后期设置。
[HttpPost]
public IActionResult MyCallMethod(MyViewModel viewModel)
{
//do something with the viewmodel here
//same page, somewhere else, do something else, etc.
}
如果您愿意,您也可以将一些标签助手用于您的标签和输入:
@Html.LabelFor(m => item.InputType, new { @class="whateverIwant" })
@Html.TextBoxFor(m => item.InputType, new { @class="form-control" })
推荐阅读
- c - c计算文件中的行数避免EOF
- flutter - Dart 的未来接口(doWhile、微任务和同步)
- python - django rest 框架中可浏览的 API 是如何工作的?
- c++ - 使用 std::variant<...> 时调用 BaseState 函数而不是 Derived 函数
- asp.net - 中间件排序
- python - 有没有办法在pygame的屏幕中心放置数字?
- azure-functions - 事件中心数据到 SQL 数据仓库 (Synapse)
- css - Jupyter QtConsole:通过配置选择内置 CSS 之一作为默认值
- c# - .net Core Newtonsoft.Json 出现“调用目标引发异常”错误
- python - 如果满足条件,则将嵌套列表的最后一个元素附加到另一个嵌套列表中