asp.net-mvc asp.net mvc 单选按钮状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/263336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 22:50:08  来源:igfitidea点击:

asp.net mvc radio button state

asp.net-mvcui-helper

提问by Josh Bush

I'm trying out asp.net mvc for a new project, and I ran across something odd. When I use the MVC UI helpers for textboxes, the values get persisted between calls. But, when I use a series of radio buttons, the checked state doesn't get persisted.

我正在为一个新项目尝试 asp.net mvc,但遇到了一些奇怪的事情。当我将 MVC UI 助手用于文本框时,值会在调用之间保持不变。但是,当我使用一系列单选按钮时,选中的状态不会持久化。

Here's an example from my view.

这是我认为的一个例子。

<li>
        <%=Html.RadioButton("providerType","1")%><label>Hospital</label>
        <%=Html.RadioButton("providerType","2")%><label>Facility</label>
        <%=Html.RadioButton("providerType","3")%><label>Physician</label>
</li>

When the form gets posted back, I build up an object with "ProviderType" as one of it's properties. The value on the object is getting set, and then I RedirectToAction with the provider as a argument. All is well, and I end up at a URL like "http://localhost/Provider/List?ProviderType=1" with ProviderType showing. The value gets persisted to the URL, but the UI helper isn't picking up the checked state.

当表单被回发时,我建立了一个对象,将“ProviderType”作为它的属性之一。对象上的值正在设置,然后我将 RedirectToAction 与提供程序作为参数。一切都很好,我最终得到了一个 URL,如“ http://localhost/Provider/List?ProviderType=1”,其中显示了 ProviderType。该值被持久化到 URL,但 UI 助手没有选择选中状态。

I'm having this problem with listbox, dropdownlist, and radiobutton. Textboxes pick up the values just fine. Do you see something I'm doing wrong? I'm assuming that the helpers will do this for me, but maybe I'll just have to take care of this on my own. I'm just feeling my way through this, so your input is appreciated.

我在使用 listbox、dropdownlist和 radiobutton 时遇到了这个问题。文本框可以很好地获取值。你看到我做错了什么吗?我假设帮手会为我做这件事,但也许我只需要自己照顾。我只是感觉我的方式,所以你的意见表示赞赏。

Edit:I just found the override for the SelectList constructor that takes a selected value. That took care of my dropdown issue I mentioned above.

编辑:我刚刚找到了采用选定值的 SelectList 构造函数的覆盖。这解决了我上面提到的下拉问题。

Edit #2:I found something that works, but it pains me to do it this way. I feel like this should be inferred.

编辑#2:我发现了一些有用的东西,但这样做让我很痛苦。我觉得这个应该是推断出来的。

<li>
  <%=Html.RadioButton("ProviderType","1",Request["ProviderType"]=="1")%><label>Hospital</label>
  <%=Html.RadioButton("ProviderType", "2", Request["ProviderType"] == "2")%><label>Facility</label>
  <%=Html.RadioButton("ProviderType", "3", Request["ProviderType"] == "3")%><label>Physician</label>
</li>

Hopefully someone will come up with another way.

希望有人会想出另一种方式。

回答by David Gardiner

If you give the radio buttons the same name as the property on your model, then MVC will automatically set the checked attribute on the appropriate button.

如果您为单选按钮指定与模型上的属性相同的名称,则 MVC 将自动在相应按钮上设置选中的属性。

I think this relies on having a strongly typed Model.

我认为这依赖于具有强类型模型。

回答by Jonathan Parker

What you need is something like this in your view:

在您看来,您需要的是这样的:

<% foreach(var provider in (IEnumerable<Provider>)ViewData["Providers"]) { %>
    <%=Html.RadioButton("ProviderType", provider.ID.ToString(), provider.IsSelected)%><label><%=provider.Name%></label>
<% } %>

And then in your controller have this:

然后在你的控制器中有这个:

var providers = GetProviders();
int selectedId = (int) Request["ProviderType"]; // TODO: Use Int32.TryParse() instead
foreach(var p in providers)
{
    if (p.ID == selectedId)
    {
        p.IsSelected = true;
        break;
    }
}
ViewData["Providers"] = providers;
return View();

The Provider class will be something like this:

Provider 类将是这样的:

public class Provider
{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

回答by Cheny

I'm using vs2010 now, it works like:

我现在正在使用 vs2010,它的工作原理如下:

<%=Html.RadioButton("ProviderType","1",Model.ProviderType==1)%><label>Hospital</label> 

looks better?

看起来更好?

回答by Haacked

The form shouldn't be posting to the querystring, unless you forgot to specify the form as method="POST". How are you specifying the form? Are you using ASP.NET MVC Beta?

表单不应发布到查询字符串,除非您忘记将表单指定为 method="POST"。你是如何指定表格的?你在使用 ASP.NET MVC Beta 吗?

回答by Al Katawazi

Well logically it would not persist, there is no session state. Think of it as an entirely new page. In order to get your radio buttons to populate you need to persist back something like ViewData["ProviderType"] = 3 to have the radiobutton repopulate with its data.

从逻辑上讲,它不会持续存在,没有会话状态。将其视为一个全新的页面。为了让你的单选按钮填充你需要坚持像 ViewData["ProviderType"] = 3 这样的东西让单选按钮重新填充它的数据。

回答by Eduardo Molteni

I've made this HTML Helper extension:

我制作了这个 HTML Helper 扩展:

    <Extension()> _
    Public Function RadioButtonList(ByVal helper As HtmlHelper, ByVal name As String, ByVal Items As IEnumerable(Of String)) As String
        Dim selectList = New SelectList(Items)
        Return helper.RadioButtonList(name, selectList)
    End Function

    <Extension()> _
    Public Function RadioButtonList(ByVal helper As HtmlHelper, ByVal Name As String, ByVal Items As IEnumerable(Of SelectListItem)) As String
        Dim sb As New StringBuilder
        sb.Append("<table class=""radiobuttonlist"">")
        For Each item In Items
            sb.AppendFormat("<tr><td><input id=""{0}_{1}"" name=""{0}"" type=""radio"" value=""{1}"" {2} /><label for=""{0}_{1}"" id=""{0}_{1}_Label"">{3}</label></td><tr>", Name, item.Value, If(item.Selected, "selected", ""), item.Text)
        Next
        sb.Append("</table>")
        Return sb.ToString()
    End Function

Then in the view:

然后在视图中:

<%= Html.RadioButtonList("ProviderType", Model.ProviderTypeSelectList) %>

In the controller the option is mapped automagically using the standard:

在控制器中,选项使用标准自动映射:

UpdateModel(Provider)

Works like a charm. If you are tablephobic, change the markup generated.

奇迹般有效。如果您有餐桌恐惧症,请更改生成的标记。

回答by K.V. Sai Kishore

View:

看法:

<%=Html.RadioButton("providerType","1")%><label>Hospital</label>
<%=Html.RadioButton("providerType","2")%><label>Facility</label>
<%=Html.RadioButton("providerType","3")%><label>Physician</label>

Controller:

控制器:

public ActionResult GetType(FormCollection collection)
{
 string type=collection.Get("providerType");

  if(type=="1")
   //code
  else if(type=="2")
   //code
  else
   //code

 return View();
}