【发布时间】:2013-07-21 06:37:45
【问题描述】:
在开发 ASP.Net MVC 4 应用程序时,我遵循了 pass enum to html.radiobuttonfor MVC3 上的答案及其派生的答案,但我的问题仍然存在。
我正在创建一个编辑页面,并希望将 Status 显示为两个单选按钮“Active”和“InActive”,这些值从数据库中读取为 Enums 1 = Active , 2 = InActive。
问题是,当页面显示时,它会显示对应于数据库值的正确单选按钮,但不允许用户更改/选择其他单选按钮??
任何想法都让我发疯 (同样将 chkbox 的属性更改为 bool 会导致比此时解决的问题更多。)
控制器.....
[HttpPost]
public ActionResult Edit(NewsArticle newsArticle, int id, HttpPostedFileBase Article)
{
try
{
if (ModelState.IsValid)
{
NewsArticle savedArticle= _newsArticle.Get(id);
savedArticle.Body = newsArticle.Body;
savedArticle.Title = newsArticle.Title;
savedArticle.Status = newsArticle.Status;
if(Article == null)
{
newsArticle.ArticleImage = savedArticle.ArticleImage;
}
else
{
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
newsArticle.ArticleImage = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
savedArticle.ArticleImage = newsArticle.ArticleImage;
string imgeName = Path.GetFileName(Article.FileName);
savedArticle.ImageName = imgeName;
}
_uow.SaveChanges();
return RedirectToAction("Index");
}
查看.......
<div class="control-group">
<div class="editor-field">
<label class="control-label">Select Status :</label>
<div class="controls">
@Html.RadioButtonForEnum(n => n.Status)
</div>
</div>
</div>
助手/扩展.....
public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression
)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var names = Enum.GetNames(metaData.ModelType);
var sb = new StringBuilder();
foreach (var name in names)
{
var description = name;
var memInfo = metaData.ModelType.GetMember(name);
if (memInfo != null)
{
var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes != null && attributes.Length > 0)
description = ((DisplayAttribute)attributes[0]).Name;
}
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();
sb.AppendFormat(
"<label for=\"{0}\">{1}</label> {2}",
id,
HttpUtility.HtmlEncode(name),
radio
);
}
return MvcHtmlString.Create(sb.ToString());
}
助手正在显示标签,因为它应该从视图中调用。
枚举....
[Flags]
public enum NewsArticleStatus
{
[Display(Name = "Active")]
Active = 1,
[Display(Name = "InActive")]
Inactive = 2
}
【问题讨论】:
-
只是出于好奇,枚举是否必须具有
[Flags]属性?我认为这意味着Active和Inactive(=3) 将是一个有效值... -
不,你的权利可以被取消。
-
很抱歉,否则没有太大帮助。嗯...可能是当用户尝试选择另一个单选按钮时,页面会刷新并从数据库中重新选择值?这意味着某些 onChanged 方法应该设置该值,因此当页面刷新时,将采用设置的值而不是数据库中的值。
-
完全没有,感谢您抽出宝贵的时间,我不这么认为,因为在生成页面时选择了根据数据库的当前值。
标签: c# asp.net sql html asp.net-mvc-4