c# - MVC3 LowerCase 路由值与 UpperCase 的行为不同吗?

标签 c# asp.net-mvc-3 enums radio-button html-helper

很抱歉这里有很多代码......我尽量让它尽可能短:

我写了(主要是从这里偷来的)一个 HtmlHelper 扩展来写出一个基于枚举的 RadioButton(分组)。我还设置了我的路线图,因此它使用枚举而不是“id”等。

我有两个枚举(对于这个例子)CurrencyType 和 StatusType

当我调用 URL/GBP/Open 时,我的 HtmlHelper 正常工作并设置单选按钮的值并选中 GBP 和 Open。​​

当我调用 URL/gbp/open 时 - Helper 仍然会检查值并且似乎可以正常工作...但是当调用 RadioButton().ToHtmlString() 时“已检查”不存在???? 使用默认路由,单选按钮也仍然设置正确???

如果您对返回的 SelectList 断点,那么您可以看到所选的选项设置正确,所以我有点困惑问题出在哪里?


Empty MVC3 website called Area36...Area 51 was taken ;)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq.Expressions;
using System.Text;

namespace Area36.Models
{
    public static class Extensions
    {
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                         select new { ID = e, Name = e };
            return new SelectList(values, "Id", "Name", enumObj);
        }

        public static void AppendFormatLine(this StringBuilder sb, string format, params object[] args)
        {
            sb.AppendFormat(format, args);
            sb.AppendLine();
        }

        public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string fieldSet)
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var e = (TProperty)Enum.Parse(typeof(TProperty), metaData.Model.ToString());
            var selectList = e.ToSelectList();
            var sb = new StringBuilder();

            if (selectList != null)
            {
                sb.AppendFormatLine("<fieldset><legend>{0}</legend>", fieldSet);
                foreach (SelectListItem item in selectList)
                {
                    var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
                    if (htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix != string.Empty)
                        id.Insert(0, string.Format("{0}_", htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix));

                    var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
                    var radio = htmlHelper.RadioButton(name: metaData.PropertyName, value: item.Value, isChecked: item.Selected, htmlAttributes: new { id = id }).ToHtmlString();

                    sb.AppendFormatLine("<div class=\"radio_{0}\">{1}{2}</div>", metaData.PropertyName, radio, label);
                }
                sb.AppendLine("</fieldset>");
            }

            return MvcHtmlString.Create(sb.ToString());
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Area36.Models;

namespace Area36.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index(CurrencyType currency, StatusType status)
        {
            return View(new ViewModel { Currency = currency, Status = status });
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Area36.Models
{
    public class ViewModel
    {
        public CurrencyType Currency { get; set; }
        public StatusType Status { get; set; }
    }
}

@using Area36.Models
@model Area36.Models.ViewModel


@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@Html.RadioButtonForEnum(m => m.Currency, "Currency")
@Html.RadioButtonForEnum(m => m.Status, "Status")

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{currency}/{status}", // URL with parameters
                new { controller = "Home", action = "Index", currency = CurrencyType.EUR, status = StatusType.Closed} // Parameter defaults
            );

        }

最佳答案

我尝试了多种方法来解决这个问题。强制传递 UpperCase 值。最令人惊讶的是,当我如下所示为所有单选按钮传递“true”时,即使输出相同,按钮也只检查大写 url。

var radio = htmlHelper.RadioButton(metaData.PropertyName, item.Value, true, new { id = id }).ToHtmlString();

通过使用此代码和一些谷歌搜索,我找到了 this . 如果你检查 以下是来自 MVC3-rtm 的代码。在这里你可以看到 isChecked 的值根据 ModelState 进行了修改,如果你在 Debug模式下检查 modelState.Values[index].AttemptedValue 的值,它显然是小写的(对于“gbp/open”)。这就是小写 url 不呈现选中属性的原因。

private IHtmlString BuildRadioButton(string name, object value, bool? isChecked, IDictionary<string, object> attributes) {
        string valueString = ConvertTo(value, typeof(string)) as string;

        TagBuilder builder = new TagBuilder("input");
        builder.MergeAttribute("type", "radio", true);
        builder.GenerateId(name);
        builder.MergeAttributes(attributes, replaceExisting: true);

        builder.MergeAttribute("value", valueString, replaceExisting: true);
        builder.MergeAttribute("name", name, replaceExisting: true);

        var modelState = ModelState[name];
        string modelValue = null;
        if (modelState != null) {
            modelValue = ConvertTo(modelState.Value, typeof(string)) as string;
            isChecked = isChecked ?? String.Equals(modelValue, valueString, StringComparison.OrdinalIgnoreCase);
        }

        if (isChecked.HasValue) {
            // Overrides attribute values
            if (isChecked.Value) {
                builder.MergeAttribute("checked", "checked", true);
            }
            else {
                builder.Attributes.Remove("checked");
            }
        }

        AddErrorClass(builder, name);

        return builder.ToHtmlString(TagRenderMode.SelfClosing);
    }

关于c# - MVC3 LowerCase 路由值与 UpperCase 的行为不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7399357/

相关文章:

jquery - MVC3/4 验证隐藏字段

c# - 在 MVC、C# 中的每个请求中运行一个方法?

c# - Enum.Parse 无法将类型 'object' 隐式转换为存在显式转换(是否缺少强制转换?)

C# Hue Bridge PUT 发送 OK 响应。无 API 响应

c# - 在 C# 中,使用自定义源时出现文本框问题

c# - Win32 异常 : "Access is denied" when trying to execute LINQ query over Process. GetProcesses()

c# - 从巨大的数据库表中读取

符合单一协议(protocol)的 Swift Enum 关联值

swift - 如何记录带有参数的枚举案例?

c# - 从 WCF 服务读取全局应用程序属性