我有一個名爲ProductController的Controller。控制器代碼如下:ASP.NET MVC 2.0 - ViewModel中的數據在發佈後丟失
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Services.Abstract;
using Web.Models;
using Ninject;
using Services.Entities;
namespace Web.Controllers
{
public class ProductController : Controller
{
IProductRepository productRepository;
public ProductController(IProductRepository products)
{
productRepository = products;
}
[HttpGet]
public ActionResult Create() {
Product p = new Product {
Id = 5
};
string theTitle = "The Title";
var viewModel = new ProductViewModel {
Product = p,
TheTitle = theTitle
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(ProductViewModel pvm) {
if (ModelState.IsValid) {
int result = productRepository.SaveProduct(pvm.Product);
return Content(result.ToString());
}
else {
return View(pvm);
}
}
}
}
我正在使用ViewModel模式將各種信息位發送到視圖。例如,我發送的產品默認Id設置爲5,並且我還設置了標題屬性[Aside:This is not production code - just test data :-)]
目前爲止都很好。當第一次調用/ Product/Create時,我的Title屬性將顯示在視圖上,並且Product Id默認爲5.但是,當我發佈表單時,僅保留了Product信息。如果ModelState無效,我再次向用戶顯示視圖。但是,這一次,標題不顯示(它被設置爲空)。該產品確實按預期顯示。
如果可能,我想在模型狀態無效時將原始標題發送回視圖。有沒有辦法做到這一點,而不使用Session,ViewData和TempData?
的問候,並感謝提前
您是否在表單上設置標題...當您回發...如果您不是...請在發佈之前再次將其設置爲視圖中的默認值... – Vishal 2010-07-13 16:22:32
不可以。不要試圖在表單上設置標題。我上面的例子可能有點愚蠢,因爲你可能永遠不會通過ViewModel實際發送像標題一樣的視圖。但是,我可以看到一種情況,我需要將其他內容傳遞給需要在帖子之間保留的ViewModel。 – 2010-07-13 16:39:16
嗯..所有我能想到的是隱藏的領域,以保留信息...但我已經完成視圖模型從一個行動張貼到其他...它應該工作,除非...也許一些名稱問題... mvc是相當奇怪有時...也許包括你試圖在視圖上做什麼? – Vishal 2010-07-13 17:39:42