當我使用默認模型綁定將表單參數綁定到作爲動作參數的複雜對象時,框架會記住傳遞給第一個請求,意味着對該操作的任何後續請求都會獲得與第一個相同的數據。參數值和驗證狀態在不相關的Web請求之間持續存在。ASP.NET MVC Beta 1:DefaultModelBinder在無關請求之間錯誤地持久參數和驗證狀態
這裏是我的控制器代碼(service
代表訪問該應用的後端):
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
return View(RunTime.Default);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(RunTime newRunTime)
{
if (ModelState.IsValid)
{
service.CreateNewRun(newRunTime);
TempData["Message"] = "New run created";
return RedirectToAction("index");
}
return View(newRunTime);
}
我的.aspx視圖(強類型爲ViewPage<RunTime
>)包含這樣的指令:
<%= Html.TextBox("newRunTime.Time", ViewData.Model.Time) %>
這使用DefaultModelBinder
類,即meant to autobind my model's properties。
我點擊頁面,輸入有效的數據(例如time = 1)。該應用程序正確保存新對象的時間= 1。然後我再次點擊它,輸入不同的有效數據(例如時間= 2)。但是,保存的數據是原始數據(例如時間= 1)。這也會影響驗證,所以如果我的原始數據無效,那麼我將來輸入的所有數據都將被視爲無效。重新啓動IIS或重建我的代碼刷新持久狀態。
我可以通過編寫我自己的硬編碼模型綁定器來解決這個問題,這個基本的簡單例子如下所示。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([ModelBinder(typeof (RunTimeBinder))] RunTime newRunTime)
{
if (ModelState.IsValid)
{
service.CreateNewRun(newRunTime);
TempData["Message"] = "New run created";
return RedirectToAction("index");
}
return View(newRunTime);
}
internal class RunTimeBinder : DefaultModelBinder
{
public override ModelBinderResult BindModel(ModelBindingContext bindingContext)
{
// Without this line, failed validation state persists between requests
bindingContext.ModelState.Clear();
double time = 0;
try
{
time = Convert.ToDouble(bindingContext.HttpContext.Request[bindingContext.ModelName + ".Time"]);
}
catch (FormatException)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName + ".Time", bindingContext.HttpContext.Request[bindingContext.ModelName + ".Time"] + "is not a valid number");
}
var model = new RunTime(time);
return new ModelBinderResult(model);
}
}
我錯過了什麼嗎?我不認爲這是一個瀏覽器會話問題,因爲如果第一個數據在一個瀏覽器中輸入,而第二個數據在另一個瀏覽器中輸入,我可以重現該問題。
這件事發生在我身上。我花了很長時間才弄明白。 將來,讓MvcContrib使用他們的WindsorContainer擴展方法註冊您的控制器。 – 2008-10-28 14:26:43