控制器
public ActionResult Create()
{
return View(new PageViewModel());
}
[HttpPost]
public ActionResult Create(Page page)
{
try
{
repPage.Add(page);
repPage.Save();
return RedirectToAction("Edit");
}
catch
{
return View(new PageViewModel());
}
}
PageViewModel
public class PageViewModel
{
public Page Page { get; set; }
public List<Template> Templates { get; set; }
private TemplateRepository repTemplates = new TemplateRepository();
public PageViewModel()
{
Page = new Page();
Templates = repTemplates.GetAllTemplates().ToList();
}
}
我的观点的一部分
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Website.Models.PageViewModel>" %>
<%= Html.TextBoxFor(model => model.Page.Name, new { @style = "width:300px;" })%>
<%= Html.DropDownListFor(model => model.Page.Template, new SelectList(Model.Templates, "ID", "Name"), new { @style = "width:306px;" })%>
模板:
ID
名称
网页:
ID
名称
TemplateID
我的下拉列表在视图中正确填充,没有任何问题。我的问题是我没有从下拉列表中获取所选值。
在我的控制器中,我在Edit
中放置了一个断点,并看到Name
文本框中填充了我输入的值。但是从下拉列表中选择的内容将设置为null。
alt text http://www.mgmweb.no/images/debug.jpg
我错过了什么,我认为它应该将正确的Template
值设置到Page
对象中。我做错了什么?
答案 0 :(得分:2)
尝试这样的事情吗? 集合中的关键是下拉列表控件的名称......
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
try
{
string selectedvalue = collection["Template"];
return RedirectToAction("Edit");
}
catch
{
return View(new PageViewModel());
}
}
答案 1 :(得分:1)
您从网页上返回的唯一内容是所选模板的ID。默认模型绑定程序不知道如何获取此标识并从存储库中检索正确的模板对象。为此,您需要实现一个自定义模型绑定器,该绑定器能够从数据库中检索值,构造一个Template对象,并将其分配给Page。或者......您可以在给定的操作中手动执行此操作,根据您在其他地方的评论,您知道如何从发布的值中获取模板的ID。
答案 2 :(得分:0)
好的,我确实喜欢这个:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
Page page = new Page();
page.Name = collection["Page.Name"];
page.TemplateID = int.Parse(collection["Page.Template"]);
page.Created = DateTime.Now;
repPage.Add(page);
repPage.Save();
return RedirectToAction("Edit");
}
catch
{
return View(new PageViewModel());
}
}
它运作良好,我只是想知道是否有更好的方法来实现这一点,而无需手动从集合中获取值。
但我想如果没有制作自己的模型活页夹就不可能像tvanfosson说的那样。
谢谢大家。
答案 3 :(得分:0)
用于模型绑定,在ActionResult中使用:
partial ActionResult(FormCollection form)
{
Page page = new Page();
UpdateModel(page);
return view(page);
}
你的班级:
public class Page
{
public string Name {get; set;}
public int Template {get; set;}
public DateTime Created {get; set;}
public Page()
{
this.Created = DateTime.Now;
}
}
您的类中的属性名称应该等于视野的名称