You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC:跳转至创建页并自动填充ProjectID字段

问题修复方案

1. 简化ActionLink的路由参数

无需传递InternalComments参数,仅保留ProjectID即可,减少冗余:

@Html.ActionLink(
    "Add a New Comment",
    "Create",
    "InternalComments",
    new { ProjectID = Model.ProjectID },
    new { @class = "btn btn-info" })

2. 修正InternalComments控制器的Create方法

需要完成三个核心操作:

  • 重新构建项目ID的下拉选项列表
  • 将接收到的ProjectID赋值给模型并传递给视图
  • 统一参数名与路由参数保持一致(规范写法)

修改后的代码:

// GET: InternalComments/Create
[HttpGet]
public IActionResult Create([FromQuery] int ProjectID)
{
    // 构建下拉选项列表,绑定PIF表的ProjectID
    ViewBag.ProjectIDList = new SelectList(_context.PIF, "ProjectID", "ProjectID");
    
    // 初始化模型并设置ProjectID
    InternalComments model = new InternalComments();
    model.ProjectID = ProjectID;
    
    // 将模型传递给视图,让控件能读取到值
    return View(model);
}

3. 确保视图正确绑定模型与选项

视图中的select控件通过asp-for绑定模型的ProjectID,同时通过asp-items读取下拉选项列表,即可自动选中对应值:

<div class="ProjID">
<div class="row justify-content-start">
    <div class="col">
        <div class="form-group">
            <label asp-for="ProjectID" class="control-label"></label>
            <select asp-for="ProjectID" class="form-control" asp-items="ViewBag.ProjectIDList"></select>
        </div>
    </div>
</div>
</div>

问题根源说明

  • 原控制器未将模型传递给视图,导致asp-for无法读取到设置的ProjectID值
  • 原控制器未初始化ViewBag.ProjectIDList,下拉列表无选项,无法完成选中操作
  • 路由参数传递冗余,无关参数可能引发潜在冲突

内容的提问来源于stack exchange,提问作者Sally Parkes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 08:42:46