c# – MVC3 LowerCase路由值的行为与UpperCase不同?
作者:互联网
在这里为很多代码道歉……我试图尽可能地保持它:
我写了(主要是从这里偷来的)一个HtmlHelper扩展来写出一个基于枚举的RadioButton(分组).我还设置了路线图,因此它使用枚举而不是“id”等.
我有两个枚举(对于此示例)CurrencyType和StatusType
当我调用URL / GBP / Open时,我的HtmlHelper正常工作并设置单选按钮的值,并选中GBP和Open.
当我调用URL / gbp / open时 – Helper仍会检查值并且似乎工作…但是当调用RadioButton().ToHtmlString()时,“checked”不存在????
使用默认路由,单选按钮仍然正确设置???
如果您断开返回的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();
随着一些rnd与这个代码和一些谷歌搜索我发现this.
如果你检查
以下是MVC3-rtm的代码.在这里你可以看到isChecked的值是根据ModelState修改的,如果在调试模式下检查modelState.Values [index] .AttemptedValue的值,它显然是小写的(对于“gbp / open”).这就是小写url不呈现checked属性的原因.
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,enums,radio-button,asp-net-mvc-3,html-helper 来源: https://codeday.me/bug/20190709/1418399.html