我想在Asp.Net MVC 3.0中顯示一個RadioButtonList。這是我的擴展方法:爲什麼列表<SelectListItem>在發佈後變爲空?
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq.Expressions;
using System.Text;
public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
StringBuilder stringBuilder = new StringBuilder();
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
if (selectList != null)
{
foreach (var item in selectList)
{
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id });
stringBuilder.AppendFormat("<div class=\"RadioButton\">{0}{1}</div>",radio.ToHtmlString(),label.ToHtmlString());
}
}
return new MvcHtmlString(stringBuilder.ToString());
}
}
這些都是我的HomeController action方法:
public ActionResult Index()
{
return View(GetIndexViewModel());
}
private IndexViewModel GetIndexViewModel()
{
List<SelectListItem> list = new List<SelectListItem>
{
new SelectListItem{ Selected = true, Value = "1", Text = "Sunday" },
new SelectListItem{ Selected = false, Value = "2", Text = "Monday" },
new SelectListItem{ Selected = false, Value = "3", Text = "Tuesday" },
new SelectListItem{ Selected = false, Value = "4", Text = "Wednesday" },
new SelectListItem{ Selected = false, Value = "5", Text = "Thursday" },
new SelectListItem{ Selected = false, Value = "6", Text = "Friday" },
new SelectListItem{ Selected = false, Value = "7", Text = "Saturday" },
};
return new IndexViewModel { SelectLists = list, SelectedItem = list[0] };
}
[HttpPost]
public ActionResult Index(IndexViewModel indexViewModel)
{
return View(GetIndexViewModel()); //this works
return View(indexViewModel); //why this doesn't work??
}
這是我index.cshtml:
@model IndexViewModel
@using (Html.BeginForm())
{
<h2>Select any one item</h2>
@Html.RadioButtonForSelectList(model => model.SelectedItem.Value, Model.SelectLists)
<br />
<input type="submit" value="Submit" />
}
我評論過這一個工作,哪一個沒有。基本上我的列表變爲空。我究竟做錯了什麼?如果我必須每次都這樣做,那麼最好使用webforms,因爲webforms可以保留回發中的數據。使用MVC基本上意味着每次發佈值時都必須進行數據庫調用。我是正確的還是在我的代碼中有一些錯誤?
是否很難將參數編寫爲camelCase? – Phill
@菲爾:對不起,我沒有明白你的意思;) – Jaggu