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

如何在.NET Core Web应用中修改查询字符串传递的参数键?

解决方案

方法一:改用Html.TextBox手动指定name

Html.TextBoxFor会基于模型表达式自动生成name属性,覆盖你手动设置的值,所以直接改用Html.TextBox来控制name:

视图代码:

<div class="form-item-container">
  @Html.LabelFor(m => m.BookingFormFields.FirstName, new { @class = "form-item-label" })
  @Html.TextBox("fn", Model.BookingFormFields.FirstName, new { @class = "form-item" })
  @Html.ValidationMessageFor(m => m.BookingFormFields.FirstName, null, new { @class = "error-text" })
</div>

提交后会生成?fn=Test的查询字符串。

后端绑定有两种方式:

  1. 直接接收参数:在Action中添加对应参数,手动赋值给模型
public IActionResult Submit(string fn)
{
    var model = new YourViewModel();
    model.BookingFormFields.FirstName = fn;
    // 其他逻辑
    return View(model);
}
  1. 自动模型绑定:给模型属性添加绑定特性,让框架自动映射fn到FirstName
  • ASP.NET Core 使用[BindProperty(Name = "fn")]:
public class BookingFormFields
{
    [BindProperty(Name = "fn")]
    public string FirstName { get; set; }
    // 其他属性
}
  • ASP.NET MVC 使用[Bind(Name = "fn")]:
public class BookingFormFields
{
    [Bind(Name = "fn")]
    public string FirstName { get; set; }
    // 其他属性
}

之后Action直接接收视图模型即可自动绑定:

public IActionResult Submit(YourViewModel model)
{
    // model.BookingFormFields.FirstName 已自动赋值为fn的参数值
    return View(model);
}

方法二:使用Tag Helper(ASP.NET Core)

如果用ASP.NET Core的Tag Helper,可以直接手动设置name属性,并用asp-value绑定模型值:

<div class="form-item-container">
  <label asp-for="BookingFormFields.FirstName" class="form-item-label"></label>
  <input type="text" name="fn" asp-value="@Model.BookingFormFields.FirstName" class="form-item" />
  <span asp-validation-for="BookingFormFields.FirstName" class="error-text"></span>
</div>

这种方式生成的input name为fn,同时保留模型验证的相关属性,后端绑定逻辑和方法一一致。

方法三:自定义EditorTemplate(进阶)

如果需要批量处理多个字段,可创建自定义EditorTemplate来统一控制name属性:

  1. 在Views/Shared/EditorTemplates目录下创建CustomInput.cshtml:
@model object
<input type="text" 
       name="@ViewData["CustomName"]" 
       value="@Model" 
       class="form-item"
       data-val="@ViewData.ModelMetadata.IsRequired"
       data-val-required="@ViewData.ModelMetadata.GetDisplayName() 不能为空" />
  1. 在视图中调用模板并指定自定义name:
<div class="form-item-container">
  @Html.LabelFor(m => m.BookingFormFields.FirstName, new { @class = "form-item-label" })
  @Html.EditorFor(m => m.BookingFormFields.FirstName, "CustomInput", new { CustomName = "fn" })
  @Html.ValidationMessageFor(m => m.BookingFormFields.FirstName, null, new { @class = "error-text" })
</div>

这种方式适合需要统一修改多个输入框name格式的场景,同时保留验证逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 12:28:23