如何更改使用checkboxfor生成的隐藏字段的名称

时间:2017-08-26 11:21:59

标签: asp.net-mvc

我有像贝洛一样的部分视图

@model IEnumerable<elearnerhub.Common.Entities.ViewModel.elearnerhub.vm_eLearning_Master_QuestionSet_AnswerOptions>

    @foreach (var item in Model)
    {
        <div class="form-group">
            @Html.LabelFor(m => item.AnswerShownOrder,item.AnswerShownOrder.ToString(), new { @class = "control-label col-md-3 col-sm-3 col-xs-12" })
            <div class="col-md-4 col-sm-4 col-xs-4">
                @Html.TextBoxFor(m => item.AnswerOptionText, new { @class = "form-control", @id=item.PK_MasterQuestion_AnswerOptionID, Name = "AnswerOptionText" })


            </div>
            <div class="col-md-2 col-sm-2 col-xs-2">

                @Html.CheckBoxFor(m => item.CorrectAnswer, new { @class = "form-control", @id = "chk"+item.PK_MasterQuestion_AnswerOptionID, @Name = "CorrectAnswer" })

            </div>
        </div>
    }

public PartialViewResult _QuestionAnswerOptions(Int64 noofoptions)
    {

        List<vm_eLearning_Master_QuestionSet_AnswerOptions> _vm_eLearning_Master_QuestionSet_AnswerOptions = new List<vm_eLearning_Master_QuestionSet_AnswerOptions>();


        for(int i = 0; i <= noofoptions-1; i++)
        {
            var obj = new vm_eLearning_Master_QuestionSet_AnswerOptions
            {
                PK_MasterQuestion_AnswerOptionID= i + 1,
                AnswerShownOrder=i+1,
                AnswerOptionText="",
                CorrectAnswer=false


            };
            _vm_eLearning_Master_QuestionSet_AnswerOptions.Add(obj);
        }

        return PartialView("_QuestionSet_AnswerOptions");
    }

隐藏字段生成带有不同名称的复选框。请参阅inspect元素的屏幕截图

enter image description here

如何设置隐藏字段的名称与复选框相同?

1 个答案:

答案 0 :(得分:0)

您可以将此简单代码段用作解决方案 -

此处.dropDownClass应该是您用于 dropdown

的课程

$('body').on('change', '.dropDownClass', function() {
  var naMe = $('#chk1').attr('name')
  $('#chk1').parent().find('input[type="hidden"]').attr('name', naMe)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name="" id="" class="dropDownClass">
	<option value="1">1</option>
	<option value="2">2</option>
</select>

<div class="col-md-2">
  <input id="chk1" class="form-control" name="CorrectAnswer" data-value="true" value="true" type="checkbox">
  <input name="item.CorrectAnswer" value="false" type="hidden">
</div>

我希望这会对你有所帮助,如果还有其他的事情请来询问。