将IEnumerable传递给视图以生成表单,然后将表单数据传递回控制器

时间:2019-09-21 01:12:54

标签: c# asp.net-core model-view-controller

我正在为我的办公室设计一个项目。我要寻找的最终结果是从数据库中提取样板字母,提取需要特定输入的部分,从这些部分生成表单,然后该表单返回用户数据,并使用用户数据集成到字母文本中。

例如,从数据库中提取的字符串看起来像这样

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 中并将其返回给控制器,但我想不出一种方法来获取C#以允许我初始化List 并将值加载到视图中。我知道我一定要丢失一些东西,但是此时我有点迷失了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您要将视图模型传递回页面吗?看来您是在从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" })
相关问题