RadioButtonFor不选择在编辑模板值 [英] RadioButtonFor not selecting value in editor templates

查看:146
本文介绍了RadioButtonFor不选择在编辑模板值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

public class Person
{
    public string Name { get; set; }
    public string Gender { get; set; }
}

我想默认的性别是女性,所以我设置了在行动:

I want the default gender to be female, so I set that up in the action:

public ActionResult Create()
{
    var model = new Person { Gender = "F" }; // default is female
    return View(model);
}

最后,视图呈现的一切是这样的:

Finally, the view renders everything like this:

@model Person

@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <p><input type="submit" value="Create" /></p>
}

如预期这一切工作。现在,让我们说,而不是简单的文本框,我想要显示的性别作为一个更直观的对单选按钮。所以,我提出以下模板,并将其保存到共享/ EditorTemplates / Gender.cshtml:

This all works as expected. Now, let's say that instead of a simple textbox, I want to display the gender as a more intuitive pair of radio buttons. So I make the following template and save it to Shared/EditorTemplates/Gender.cshtml:

@model string
@Html.RadioButtonFor(model => model, "F") Female
@Html.RadioButtonFor(model => model, "M") Male

最后,我用装饰性别[UIHint(性别)]

性别上现在可以正确使用单选按钮,这是伟大的呈现,但...

Gender is now properly rendered with radio buttons, which is great, BUT...

问题

女性不再来选择作为默认值pre,而是我结束了空白两个单选按钮。我缺少的东西吗?

Female no longer comes pre selected as the default value and instead I end up with the two radio buttons blank. Am I missing something?

有趣的是,如果我将 RadioButtonFor 从模板到视图(改变模式=&GT;模型模式=&GT; model.Gender ),则一切正常。我知道这是一个可行的解决办法,但这些模板助手是这样一个惊人的,令人上瘾的方便,我会宁愿让他们走之前用尽所有的可能性。

Interestingly, if I move RadioButtonFor from the template to the view (changing model => model to model => model.Gender), then everything works as expected. I know this is a viable workaround, but these templated helpers are such an amazing, addictive convenience that I would rather exhaust all possibilities before letting them go.

推荐答案

我知道这是丑陋的,但以下可能的工作:

I know it's ugly but the following might work:

@model string
@Html.RadioButton("", "F", Model == "F") Female
@Html.RadioButton("", "M", Model == "M") Male

与单选帮手的问题是,如果第一个参数为空或空它会永远把它作为非托运从而使这一帮手不适合编辑模板。

The problem with the RadioButton helper is that if the first argument is null or empty it will always consider it as non checked thus making this helper inappropriate for editor templates.

下面是一个从MVC源$ C ​​$ C的摘录这说明我的意思:

Here's an excerpt from the MVC source code which illustrates what I mean:

bool isChecked = !string.IsNullOrEmpty(name) && string.Equals(htmlHelper.EvalString(name), b, StringComparison.OrdinalIgnoreCase);

作为一种替代方法,你可以使用<一个href=\"http://stackoverflow.com/questions/2512809/has-anyone-implement-radiobuttonlistfort-for-asp-net-mvc/2590001#2590001\">custom HTML辅助产生单选按钮的列表。

这篇关于RadioButtonFor不选择在编辑模板值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆