MVC RadiobuttonFor Razor如何使标签点击?

时间:2016-03-22 09:07:43

标签: c# razor asp.net-mvc-5 html-helper

到目前为止,我正试图用剃刀语法创建一个radiobuttonlist我已经想出了这个

UPDATE Table1
INNER JOIN Table2 ON ( Table1.PostCode = REPLACE(Table2.PostCode,' ',''))
SET Table1.StreetName = Table2.StreetName

但标签与radiobutton无关。

2 个答案:

答案 0 :(得分:1)

您的foreach循环没有为标签生成for属性(如果您从new { id = p.id.ToString() }方法移除了RadioButton,则不会有id属性虽然这是默认行为,但仍然添加了。

当您的模型为IEnumerable<T>时未添加属性的原因是符合HTML-4标准,该标准指出

  

ID令牌必须以字母([A-Za-z])

开头

HtmlHelpers根据id属性生成name属性,但用下划线替换[].个字符防止与jQuery选择器发生冲突(例如,.属性中的id将被解释为类名选择器。在您的情况下,name对于集合中的第一个项目为name="[0].Name",但因为这意味着生成id="_0__Name"(在HTML-4中无效),HtmlHelper只是省略id(如果是label,则为for属性。

解决此问题的一种简单方法是将单选按钮包装在<label>元素

<label>
    @Html.RadioButton("name", "1", false)
    <span>@p.name</span>
</label>

另一种选择是在id中生成RadioButton()属性,并在标签中生成匹配的for属性

@Html.RadioButton("name", "1", false, new { onclick = "ShowOption(this)", id = p.id })
@Html.Label(p.name, new { @for = p.id})

附注:我建议您使用强力输入的RadioButtonFor()LabelFor()方法。

答案 1 :(得分:0)

寻找这条线 @ Html.Label(“ some label”,htmlAttributes:new {onclick =“ ShowOption(” someID“);”,id =“ someID”})

<script type="text/javascript">
 function ShowOption(id) {
 /* do something */
}
</script>

    @{
        ViewBag.Title = "Home Page";
    }

    <div class="jumbotron">
        <h1>ASP.NET</h1>
        <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
        <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
    </div>

    <div class="row">
        <div class="col-md-4">
            <h2>Getting started</h2>

            @Html.Label("some label",htmlAttributes: new { onclick = "ShowOption("someID");", id = "someID" })

            <p>
                ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
                enables a clean separation of concerns and gives you full control over markup
                for enjoyable, agile development.
            </p>
            <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
        </div>
        <div class="col-md-4">
            <h2>Get more libraries</h2>
            <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
            <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
        </div>
        <div class="col-md-4">
            <h2>Web Hosting</h2>
            <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
            <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
        </div>
    </div>