繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM