c# - 使用 Razor 在 MVC 中发布复杂对象列表

标签 c# .net asp.net-mvc post razor

情景:
首先,对不起我的英语。 我想做的是通过表单发布 - 发布以下对象:

public class AppConfigViewModelInput
{
    public string Setting { get; set; }
    public string Value { get; set; }
}

以下方法:

    [HttpPost]
    public ActionResult Index(List<AppConfigViewModelInput> listOfAppConfigToUpdate)
    { ... }

但是这个输入对象仅由我用来在 Razor 页面上显示数据的 View 对象的两个属性构成:

public class AppConfigViewModel : AppConfigViewModelInput
{
    public string Description { get; set; }
    public string ConfigType { get; set; }
    public int ViewOrderInWebAdmin { get; set; }
    public string ViewSpecialBackgroundColor { get; set; }
}

我阅读了很多问题和博客(查看问题中的 SO References)。最后,我可以为我的 razor 页面获取以下代码(我只发布了表单代码部分):

@model List<PGWebAdmin.Models.AppConfigViewModel>
@{
    var itemCnt = 0;
}
@foreach (var item in Model)
    {
        itemCnt++;
        <input type="hidden" name="AppConfigViewModelInput.Index" value="@itemCnt" />
        <input type="text" class="input-sm form-control" value="@item.Value" name="AppConfigViewModelInput[@itemCnt].Value"/>
        <input type="text" name="AppConfigViewModelInput[@itemCnt].Setting" value="@item.Setting"/>
    }

表单由以下人员创建:

    @using (Html.BeginForm("Index", "AppConfig",
   FormMethod.Post, new { @class = "navbar-form navbar-right", role = "search" }))
    { 

问题:
我可以发送数据,我正在使用开发工具检查以下信息:enter image description here

即post到方法中,命中方法,但参数值为null:

enter image description here

我测试、更正并尝试了几种方法来做到这一点,但这是我能做到的很远,我不明白发生了什么。

我做错了什么?为什么我仍然得到 null?

任何帮助都会得到返回。 谢谢!

引用资料:
MVC post a list of complex objects
How can I post a list of items in MVC
Posting to a list<modeltype> MVC3

最佳答案

您需要更改参数的名称以匹配您在“名称”字段中发送的内容。

即更改您的帖子 Controller :

[HttpPost]
public ActionResult Index(List<AppConfigViewModelInput> AppConfigViewModelInput)
    { ... }

关于c# - 使用 Razor 在 MVC 中发布复杂对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35508541/

相关文章:

c# - 为什么 c# 程序员不像 java 程序员那样被 ruby​​ 吸引

c# - 如何使用 C# 创建 4 位 PNG?

c# - Angular 5 Uncaught( promise 中): Error: StaticInjectorError(AppModule)

c# - native C++ 和 C# 互操作

.net - .Net Framework 的生命周期有多长?

c# - 使用 WebAPI 2 进行 JSON.NET 抽象/派生类反序列化

javascript - Viewbag 改变 onclick 中的值?

asp.net-mvc - 基于属性的Ajax请求错误处理? (值得吗?)

c# - 移植 C# 代码以在 OSX 上运行

c# - 通过 PartialView 方法返回 View