将List <modelobject>返回到Controller MVC

时间:2017-06-09 19:31:37

标签: c# asp.net-mvc

我意识到这个问题已被问过几次,我经历了大部分问题并最终尝试以两种不同的方式进行,但我无法弄清楚我正在处理的几个问题。 / p>

我的数据库上的表上有一个SystemSettings列表。所以我想在视图上显示这些设置,允许用户根据需要进行编辑。我试图避免以非动态的方式进行,因为系统几乎仍在不断变化,所以我们最终可以添加/删除/编辑其中的一些,我认为这样做可以节省一些未来开发工作。

这是我正在使用的ViewModel:

public class SystemSettingsViewModel
{
    public IList<SystemSetting> SystemSettings { get; set; }

    public string Message { get; set; }
}

我的对象SystemSetting看起来像:

public class SystemSetting
{
    public int Id { get; set; }

    public string Key { get; set; }

    [Required]
    [StringLength(4000)]
    public string Value { get; set; }

    public string DisplayName { get; set; }

    public string Description { get; set; }

    //I don't really use this in the view, but I need it for something else
    public short PendingOperationId { get; set; }
}

然后我在我的视图上尝试了几种不同的方法,首先我尝试使用带有for循环的索引:

@using (Html.BeginForm("Save", "SystemSettings"))
{
    for (int i = 0; i < Model.SystemSettings.Count; i++)
    {
        <div class="form-group">
            <label for=@string.Concat("setting_Value", Model.SystemSettings[i].Key) title=@Model.SystemSettings[i].Description>@Model.SystemSettings[i].DisplayName</label>
            @Html.TextBoxFor(x => x.SystemSettings[i].Value, new { @class = "form-control", id = string.Concat("setting_Value", Model.SystemSettings[i].Key) })
            @Html.ValidationMessageFor(x => x.SystemSettings[i].Value)
            @Html.HiddenFor(x => x.SystemSettings[i].Id)
            @Html.HiddenFor(x => x.SystemSettings[i].Key)
            @Html.HiddenFor(x => x.SystemSettings[i].Description)
            @Html.HiddenFor(x => x.SystemSettings[i].DisplayName)
        </div>
    }
    <button type="submit" class="btn btn-primary">Save</button>
}

我也尝试过使用EditorTemplates,留下这样的视图:

@using (Html.BeginForm("Save", "SystemSettings"))
{
    <div>
        @Html.EditorFor(m => m.SystemSettings)
    </div>
    <button type="submit" class="btn btn-primary">Save</button>
}

这样的EditorTemplate视图(SystemSetting.cshtml)

@model MyModel.SystemSetting
<div class="form-group">
    <label for=@string.Concat("setting_Value", Model.Key) title=@Model.Description>@Model.DisplayName</label>
    @Html.TextBoxFor(x => x.Value, new { @class = "form-control", id = string.Concat("setting_Value", Model.Key) })
    @Html.ValidationMessageFor(x => x.Value)
    @Html.HiddenFor(x => x.Id)
    @Html.HiddenFor(x => x.Key)
    @Html.HiddenFor(x => x.Description)
    @Html.HiddenFor(x => x.DisplayName)
</div>

我的问题是:

两种方法都像我想要的那样显示视图,除了标签中的工具提示产生一些奇怪的东西:

<label for="setting_ValueDefaultTimeoutInMilliseconds" title="Default" timeout="" in="" milliseconds.="">Default timeout (ms)</label>

当我将对象放回控制器时,我的ViewModel的成员为空。

我的控制器的签名是:

    [HttpPost]
    public ActionResult Save(SystemSettingsViewModel systemSettings)

任何指针都会非常感激。

0 个答案:

没有答案