ASP.NET Core 6 MVC中QueryString预填充的AffiliateId字段提交后模型值为空的问题
ASP.NET Core 6 MVC中QueryString预填充的AffiliateId字段提交后模型值为空的问题
问题原因
这是个很容易踩的前端小坑!问题不在ASP.NET Core的模型绑定,而是HTML的disabled属性特性:被标记为disabled的表单元素,浏览器会自动排除它的提交值,不会把这个字段的数据发送到服务器。所以你通过QueryString预填值并禁用输入框后,服务器端自然拿不到这个值;而手动输入时输入框是启用状态,值能正常提交,因此表现正常。
解决方案
有两种贴合你需求的解决方式,选一个就行:
方案1:用readonly替换disabled
readonly属性的作用是禁止用户编辑输入框内容,但不会阻止浏览器提交该字段的值,完全匹配你的场景:
<div class="col form-group"> @if (string.IsNullOrEmpty(Request.Query["AffiliateId"])) { <input asp-for="Input.AffiliateId" class="form-control" /> } else { <input asp-for="Input.AffiliateId" class="form-control" value="@Request.Query["AffiliateId"]" readonly /> } </div>
方案2:保留disabled展示,新增隐藏字段提交值
如果你更偏好disabled的视觉样式(部分UI框架会给禁用状态做特殊灰化处理),可以保留禁用的输入框用于展示,同时添加一个隐藏的input来携带预填的值提交:
<div class="col form-group"> @if (string.IsNullOrEmpty(Request.Query["AffiliateId"])) { <input asp-for="Input.AffiliateId" class="form-control" /> } else { <!-- 禁用的输入框仅用于展示,不参与提交 --> <input asp-for="Input.AffiliateId" class="form-control" value="@Request.Query["AffiliateId"]" disabled /> <!-- 隐藏字段负责把预填值提交给服务器 --> <input type="hidden" asp-for="Input.AffiliateId" value="@Request.Query["AffiliateId"]" /> } </div>
额外优化建议
你还可以简化视图里的逻辑,利用ASP.NET Core的页面模型初始化特性,把QueryString的判断逻辑移到后台,让视图代码更简洁:
在页面模型的OnGet方法里预填充值:
public void OnGet(string returnUrl = null) { if (!string.IsNullOrEmpty(Request.Query["AffiliateId"])) { Input.AffiliateId = Request.Query["AffiliateId"]; } ReturnUrl = returnUrl; }
然后视图里可以简化成:
<div class="col form-group"> <input asp-for="Input.AffiliateId" class="form-control" @(!string.IsNullOrEmpty(Input.AffiliateId) ? "readonly" : "") /> </div>
这样视图里不用写复杂的分支判断,代码更干净,也符合前后端逻辑分离的习惯~
备注:内容来源于stack exchange,提问作者c0D3l0g1c




