为什么此枚举的MVC模型绑定在回发时失败?

时间:2019-04-17 23:26:51

标签: c# asp.net-mvc-4

我有一个模型类,其值为SomeEnum

public class SomeModel
{
    public SomeEnum MyChoice { get; set; }
}

public enum SomeEnum
{
    OptionOne, OptionTwo, OptionThree
}

我有一个编辑器模板,该模板为枚举呈现了一组单选按钮:

@model Enum
@{
    var enumType = Nullable.GetUnderlyingType(ViewData.ModelMetadata.ModelType) 
                   ?? ViewData.ModelMetadata.ModelType;

    var items = Model.SelectListItems(enumType);
}
<div class="form-group">
    @foreach (var item in items)
    {
        var id = Guid.NewGuid();
        <div class="form-check">
                // also tried ViewData.ModelMetadata.PropertyName below
            @Html.RadioButton(ViewData.TemplateInfo.HtmlFieldPrefix, 
                 item.Value, 
                 item.Value.Equals(Model.ToString()), 
                 new {id, @class = "form-check-input"})
            @Html.Label(item.Text, new {@for = @id, @class = "form-check-label"})
        </div>
    }
    @Html.ValidationMessageFor(m => m)
</div>

哪个呈现为

<div class="form-group">
    <div class="form-check">
        <input id="guid1" name="MyChoice.MyChoice" checked="checked" 
               class="form-check-input" type="radio" value="OptionOne">
        <label for="guid1" class="form-check-label">Option One</label>
    </div>
    <div class="form-check">
        <input id="guid2" name="MyChoice.MyChoice" 
               class="form-check-input" type="radio" value="OptionTwo">
        <label for="guid2" class="form-check-label">Option Two</label>
    </div>
    <div class="form-check">
        <input id="guid3" name="MyChoice.MyChoice" 
               class="form-check-input" type="radio" value="OptionThree">
        <label for="guid3" class="form-check-label">Option Three</label>
    </div>
    <span class="field-validation-valid" 
          data-valmsg-for="MyChoice" data-valmsg-replace="true"></span>
</div>

我认为问题在于name属性总是将MyChoice.MyChoiceMyChoice渲染成“两倍”(与使用ViewData.ModelMetadata.PropertyName相同),但是我不能确定原因。

2 个答案:

答案 0 :(得分:1)

该解决方案原来是要替换的

@Html.RadioButton(ViewData.TemplateInfo.HtmlFieldPrefix, 
      item.Value, 
      item.Value.Equals(Model.ToString()), 
      new {id, @class = "form-check-input"})

具有:

@Html.RadioButton("", item.Value, 
      item.Value.Equals(Model.ToString()), 
      new {id, @class = "form-check-input"})

是的:替换name属性(描述为“ 表单字段的名称和用于查找值的ViewDataDictionary键”)。 一个空字符串使用会导致html中的name属性正确呈现,例如:

<input id="guid1" class="form-check-input" name="MyChoice" type="radio" value="OptionOne">

...,并且模型绑定按预期工作,将回传时将所选值作为枚举传递回模型中的表单。如果将其记录在某个地方,或者更好,不是这种方式,但是您去了,那就好了。

答案 1 :(得分:0)

将枚举转换为字符串:

const wrapper = shallowMount(ComponentB, { propsData: { ... } });

// create a spy on the instance method
const spyUpdate = jest.spyOn(wrapper.vm, 'update')

// replace the instance method with the spy
wrapper.setMethods({ update: spyUpdate });

// your tests ...

// verify the spy was called
expect(spyUpdate).toHaveBeenCalled();

// remove the spy
spyUpdate.mockReset();