How to override the “name” HtmlAttribute of Razor

2020-06-09 05:40发布

问题:

    @Html.RadioButtonFor(Model => Model.Location, "Location")
    @Html.LabelFor(Model=>Model.Location,"Location")
    @Html.RadioButtonFor(Model=>Model.Model,"Model")
    @Html.LabelFor(Model=>Model.Model,"Model")
    @Html.RadioButtonFor(Model=>Model.MovableUnit,"MU")
    @Html.LabelFor(Model=>Model.MovableUnit,"MU")




   <input id="Location" name="Location" type="radio" value="Location" />
    <label for="Location">Location</label>
    <input id="Model" name="Model" type="radio" value="Model" />
    <label for="Model">Model</label>
    <input id="MovableUnit" name="MovableUnit" type="radio" value="MU" />
    <label for="MovableUnit">MU</label>

How to have a common name="radiobtn" for all the above Radio buttons? The problem is I want to select only one radio button at a time, but in this case all are selectable at the same time.

回答1:

Just create a dummy property in your Model class like, public string Dummy{get; set;}

@Html.RadioButtonFor(Model => Model.Location, "LOC", new { @Name = "Dummy"})
@Html.RadioButtonFor(Model => Model.Model_Number, "MOD", new { @Name = "Dummy" })
@Html.RadioButtonFor(Model => Model.MovableUnit, "MU", new { @Name = "Dummy" })

Get the value "LOC", "MOD", "MU" using property name 'Dummy'.



回答2:

Use the function without "for", then you can specify the name:

@Html.RadioButton("newname", "value", new { @id="oldname" })