我无法使此列表框具有值。它在我要翻译的MVC4.5中起作用;无法在MVC Core中工作。发誓它在某个时候正在工作;现在不是。
尝试过: https://stackoverflow.com/a/19144613/2496266 https://stackoverflow.com/a/40308906/2496266 等
查看
<div class="tb-field desc-field">
@Html.ListBoxFor(model => model.workerRequests,
new SelectList(ViewBag.workerRequests, "Value", "Text"),
new { id = "workerRequests2_WO-"+ Model.ID, tabindex = "22", style="min-width: 16em;"}
)
</div>
控制器(GET)
wo.workerRequests = new List<ViewModel.WorkerRequest>();
ViewData["workerRequests"] = new SelectList(wo.workerRequests);
return PartialView("Create", wo);
控制器(POST)
public async Task<ActionResult> Create(WorkOrder wo, string userName)
{
ModelState.ThrowIfInvalid();
var modelUpdated = await _adaptor.TryUpdateModelAsync(this, wo);
// ... "wo.WorkerRequests" is empty here ^
}
实体
public virtual ICollection<WorkerRequest> workerRequests { get; set; }
其他信息:
显然,它在请求中遇到,但作为StringValue:
...显然它们都是字符串值。它并没有绑定到所需的类型。
基本上:
我们正在从数据库(嵌套类型)的WorkerRequest中选择Worker。这是由于延迟加载错误吗?我在做什么错了?
Gracias
答案 0 :(得分:0)
您似乎正在为该视图创建2个SelectList
对象。
一次进入控制器
ViewData["workerRequests"] = new SelectList(wo.workerRequests);
再次在视图中:
@Html.ListBoxFor(model => model.workerRequests,
new SelectList(ViewBag.workerRequests, "Value", "Text"),
您只需要创建一个,最好的地方就是视图。因此,更改您的控制器代码以用数据填充ViewData
并让视图创建SelectList
来显示:
ViewData["workerRequests"] = wo.workerRequests;
现在,您应该看到列表框中填充了数据。
答案 1 :(得分:0)
出于好奇,this是我们最终得到的:
public ActionResult Create(Domain.WorkOrder wo, string userName, List<Domain.WorkerRequest> workerRequestList)
{
UpdateModel(wo);
Domain.WorkOrder neworder = woServ.Create(wo, userName);
// JSON object with new work order data
var result = map.Map<Domain.WorkOrder, ViewModel.WorkOrder>(neworder);
return Json(new
{
sNewRef = result.tabref,
sNewLabel = result.tablabel,
iNewID = result.ID
},
JsonRequestBehavior.AllowGet);
}
<div class="tb-label desc-label">
@Html.LabelFor(model => model.workerRequests)
<br />
<input type="button" value="@Machete.Web.Resources.WorkOrder.requestAdd" class="formButton" id="addRequestBtn-@(Model.ID)"/>
<input type="button" value="@Machete.Web.Resources.WorkOrder.requestRemove" class="formButton" id="removeRequestBtn-@(Model.ID)"/>
</div>
<div class="tb-field desc-field">
@Html.ListBox("workerRequests2", new SelectList(ViewBag.workerRequests, "Value", "Text"), new { id = "workerRequests2_WO-"+ Model.ID, tabindex = "22", style="min-width: 16em;"})
</div>