asp.net mvc radio button state

后端 未结 7 1878
轮回少年
轮回少年 2021-02-07 19:06

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

7条回答
  •  情话喂你
    2021-02-07 19:36

    What you need is something like this in your view:

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

    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:

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

提交回复
热议问题