【问题标题】:Hidden Field Value to Server Side服务器端的隐藏字段值
【发布时间】:2019-04-19 05:59:46
【问题描述】:

我有一个表单提交,我尝试通过隐藏字段将选定的下拉值发送到服务器端,但它不起作用:

 @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @id = "registerFormId" }))
{
    <select class="form-control" id="districtId"></select>
    @Html.HiddenFor(m => m.DistrictId)
}

服务器端

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Register(RegisterViewModel registerViewModel)
    {
         // Hidden field value not bind here.
    }

注册视图模型:

public class RegisterViewModel
{
    // Some Properties there

    public int UserId { get; set; }
    public bool Status { get; set; }
    public int CountryId { get; set; }
    public bool IsGuest { get; set; }
    public int DistrictId { get; set; }
    public string ZipPostalCode { get; set; }
}

【问题讨论】:

  • 您能否确保在选择下拉值时填充隐藏字段?请在您的视图中发布您的下拉列表。
  • @TechGuy,如何将下拉选择的值设置为隐藏字段?
  • 它是因为您没有在 m.DistrictId 中设置任何内容,它只是一个隐藏字段。向我们展示您如何填充您的选择元素。
  • 这里为什么需要隐藏字段?只需将下拉列表直接绑定到您的模型即可

标签: c# jquery json asp.net-mvc


【解决方案1】:

将选择的ID更改为另一个名称,不要使用相同的名称。

<select class="form-control" id="another"></select>

必须确保在提交前选择时已设置隐藏字段的值。

$('#another').on('change', function(){
   $('#DistrictId').val($(this).val());
});

祝你好运!

【讨论】:

    【解决方案2】:

    您应该为该隐藏 ID 创建下拉列表。您不需要创建隐藏字段。

    @Html.DropDownListFor(m => m.DistrictId,                
        new List<SelectListItem> { 
        new SelectListItem { Value = "0" , Text = "Option A" },
        new SelectListItem { Value = "1" , Text = "Option B" }
        }, new { @class="classname"})
    

    【讨论】:

      猜你喜欢
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多