gpt4 book ai didi

c# - ASP MVC 模型列表 在 POST 操作中返回空
转载 作者:行者123 更新时间:2023-11-30 13:37:15 25 4
gpt4 key购买 nike

我遇到了一个很难解决的问题。我正在创建一个页面,用户将在其中看到项目列表(产品类型)。每个项目旁边都有一个下拉列表,以便用户可以做出适当的选择来创建映射。选择后,用户提交表单,值将写入数据库。

问题是当它被提交时,我没有得到任何返回值。具体来说,“映射”在 POST 操作返回的模型中为空。 GET 操作工作正常。以下是我写的精华内容:

型号:

public class ProductTypeMappingViewModel
{
//this is empty in the POST object
public List<ProductTypeMapping> Mappings { get; set; }

public ProductTypeMappingViewModel()
{
Mappings = new List<ProductTypeMapping>();
}

public ProductTypeMappingViewModel(string db)
{
//use this to populate 'Mappings' for GET action
//works fine
}

public void UpdateDB()
{
//to be called on the object
//returned from POST action
foreach(var mapping in Mappings)
{
//Mappings is always empty after POST
//Suppose to add to db
}
}
}

public class ProductTypeMapping
{
public string ProductTypeName { get; set; }
public int SelectedStandardProductTypeKey { get; set; }
public SelectList StandardProductTypes { get; set; }

public ProductTypeMapping()
{
StandardProductTypes = new SelectList(new List<SelectListItem>());
}

public int GetSelectedProductTypeKey() { //return selected key}

public string GetSelectedProductTypeName() { //return selected name}
}

查看:

@model CorporateM10.Models.ProductTypeMappingViewModel

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">

@Html.ValidationSummary(true)

<table class="table">
@foreach (var dept in Model.Mappings)
{
<tr>
<td>
@Html.DisplayFor(model => dept.ProductTypeName, new { })
</td>
<td>
@Html.DropDownListFor(model => dept.SelectedStandardProductTypeKey, dept.StandardProductTypes, "(Select Department)", new { })
</td>
</tr>
}
</table>

<div>
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
}

任何见解将不胜感激。

最佳答案

foreach 导致最终 HTML 中的 select 元素具有不正确的 name 属性。因此,没有任何内容被发布到服务器。将其替换为 for 循环:

<table class="table">
@for (int i=0; i<Model.Mappings.Count; i++)
{
<tr>
<td>
@Html.DisplayFor(model => model.Mappings[i].ProductTypeName, new { })
</td>
<td>
@Html.DropDownListFor(model => model.Mappings[i].SelectedStandardProductTypeKey, model.Mappings[i].StandardProductTypes, "(Select Department)", new { })
</td>
</tr>
}
</table>

关于c# - ASP MVC 模型列表 <object> 在 POST 操作中返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23808001/

25 4 0