[英]Passing an IEnumerable to a view to generate a form and then passing form data back to controller
我正在為我的辦公室做一個項目。 我正在尋找的最終結果是從數據庫中提取樣板字母,提取需要特定輸入的部分,從這些部分生成表單,然后表單返回用戶數據,並使用重建字母用戶數據集成到信件的文本中。
例如,從數據庫中提取的字符串如下所示
Claim #: |string^clmNum^Claim Number: | - Ref#: |string^RefNum^Reference Number: |
並在使用用戶數據重建后最終如下所示:
Claim #: 123456 - Ref#: 789012
這就是我到目前為止所做的工作......
|之間的部分被拉出、拆分並加載到 IEnumerable 中
我的 foo model 是:
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>
到目前為止,我已經完成了所有工作。 我需要獲取在動態創建的表單上輸入的數據並將其返回到 controller,以便我可以索引以重建字符串。
我試過使用類似於這個的@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> 並將其返回到 controller,但我想不出一種方法來讓 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
}
}
我還假設您在 controller 上進行了后期設置。
[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" })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.