我有一個模型和兩個的ViewModels使用視圖模型發佈到模型
型號:
public class WebPages
{
[Key]
public int WebPagesId { get; set; }
public String DomainName { get; set; }
public DateTime DomainStart { get; set; }
public DateTime DomainExp { get; set; }
}
視圖模型:
public class WebPagesViewModel
{
public String DomainName { get; set; }
public DateTime DomainStart { get; set; }
public List<SelectListItem> DurationDays { set; get; }
public int SelectedDurationDays { set; get; }
}
所以控制器這些是:
//Get controller
public ActionResult Create(WebPages model)
{
var vm = new WebPagesViewModel
{
DurationDays = new List<SelectListItem>()
{
new SelectListItem {Value = "1", Text = "1 año"},
new SelectListItem {Value = "2", Text = "2 años"}
}};
retrun View(vm);
}
//Post controller
public async Task<ActionResult> Create(WebPagesViewModel model)
{
var endDate = DateTime.Now.AddYears(model.SelectedDurationDays);
var webnew = new WebPages
{
DomainName = model.DomainName,
DomainStart = model.DomainStart,
DomainExp = endDate
};
db.WebPagesList.Add(webnew);
db.SaveChanges();
return View(model);
這工作好,我沒有任何問題MS,我想要做的是添加新的日子到現有的DomainExp
特定的DomainName
我的數據庫。
我嘗試這樣做,創建另一個視圖模型和創建視圖像這樣的:
public class RenewalViewModel
{
public int SelectedDurationDays { set; get; }
public List<SelectListItem> AddTime { get; set; }
public int SelectedWebPage { get; set; }
public IEnumerable<SelectListItem> Webpage { get; set; }
}
}
控制器:
[HttpGet]
public async Task<ActionResult> Renewal()
{
var vm = new RenewalViewModel
{
AddTime = new List<SelectListItem>
{
new SelectListItem {Value = "1", Text = "1 año"},
new SelectListItem {Value = "2", Text = "2 años"},
new SelectListItem {Value = "3", Text = "3 años"},
new SelectListItem {Value = "4", Text = "4 años"},
new SelectListItem {Value = "5", Text = "5 años"},
new SelectListItem {Value = "6", Text = "6 años"},
new SelectListItem {Value = "7", Text = "7 años"},
new SelectListItem {Value = "8", Text = "8 años"},
new SelectListItem {Value = "9", Text = "9 años"}
},
Webpage = new SelectList(db.WebPagesList,"WebPagesId", "DomainName")
};
return View(vm);
}
[HttpPost]
public async Task<ActionResult> Renewal(RenewalViewModel vm)
{
var addDays = DateTime.Now.AddYears(vm.SelectedDurationDays);
var webpage = new WebPages
{
DomainExp = addDays
};
db.Entry(webpage).State = EntityState.Modified;
return View(webpage);
}
但return View(webpage);
我有這個問題
XXX型號.Webpages不能分配給模型類型xxx.Models.ViewModel.RenewalViewModel
我知道這是因爲我在我看來RenewalViewmodel而不是網頁叫,我想知道什麼是我的錯步這樣做,我想
視圖中的模型是@model RenewalViewModel,因此您需要返回一個'RenewalViewModel',而不是'WebPages'模型 - 即'return View(vm);' –
但在這種情況下我該如何比較'大教堂如果'DomainExp'進入了'WebPages'模型 – Eduard
對不起,我不理解您的評論 - 沒有在您的'續訂'方法或相關視圖模型中的任何現有'WebPages'的引用 - 你所有正在創建並保存一個新的「WebPages」。 –