【发布时间】:2011-01-20 04:47:17
【问题描述】:
我不确定我是否从我的 ASP.NET MVC 应用程序中正确发布了多个部分页面。
在我的网站上,我加载了一些部分页面并将它们显示在 jQuery UI 选项卡中。这是我的 Index.aspx 页面中的示例(人为示例):
<div id="tabScenario"><% Html.RenderPartial("Scenario", Model); %></div>
<div id="tabPerson"><% Html.RenderPartial("Person", Model.People.FirstOrDefault()); %></div>
<div id="tabAddress"><% Html.RenderPartial("Address", Model.People.FirstOrDefault().Addresses.FirstOrDefault()); %></div>
我的部分视图都被强类型化为每个对象的单数版本(在本例中为场景、人员和地址)。
用户输入他或她想要更改的数据,然后保存数据。当我发布该数据时,我在我的控制器中执行此操作:
[HttpPost]
[Header("Setup Scenario")]
public ActionResult Index(Scenario scenario, Person person, Address address, string submitButton)
{
// Update the scenario with all the information that belongs to it.
scenario.Person = person;
scenario.Person.Address = address;
// Determine whether to just save or to save and submit.
switch (submitButton)
{
case "Save":
return Save(scenario, true);
case "Save As...":
return Save(scenario, false);
case "Submit":
return Submit(scenario);
default:
return View();
}
}
我不完全确定这是多么正确,因为当我在下一个视图中显示我刚刚发布的信息时,我在线收到以下运行时错误:
<div id="tabPerson"><% Html.RenderPartial("Person", Model.People.FirstOrDefault()); %></div>
错误:
传入的模型项 字典是类型 'Mdt.ScenarioDBModels.Scenario',但是 这本词典需要一个模型项 类型为“Mdt.ScenarioDBModels.Person”。
让我感到困惑的是,如果你看一下特定的行,我得到的是 Person。因此,根据这篇文章,它告诉我我的值很可能是 null 并且 ASP.NET 正在“回退”到 Scenario 对象。
由于这一切,我认为我在发布所有数据的方式上做错了(有很多数据),但我被困在了那个地方。
澄清
我通过 Ajax 发布。这是 BeginForm 语句。
<% using (Ajax.BeginForm("Index", "Scenario", new AjaxOptions { HttpMethod = "Post", OnSuccess = "scenarioSubmitSuccess" }, new { id = "scenarioForm" }))
{ %>
// My Index.aspx
<% } %>
Save 方法基本上是尝试将模型保存到后备存储(在本例中为数据库)。方法如下:
/// <summary>
/// Save a the scenario.
/// </summary>
/// <param name="scenario">The scenario to save to the database.</param>
/// <param name="overwrite">True if the existing scenario should be updated in the database.</param>
/// <returns></returns>
private ActionResult Save(Scenario scenario, bool overwrite)
{
if (ModelState.IsValid && TryUpdateModel(scenario, "Scenario"))
{
ScenarioDBEntities entities = ObjectContextFactory.GetScenarioDBEntities();
ScenarioRepository scenarioRepository = new ScenarioRepository(entities);
if (overwrite)
{
scenarioRepository.Update(scenario);
}
else
{
scenarioRepository.Add(scenario);
}
entities.SaveChanges();
}
return View(scenario);
}
【问题讨论】:
-
您需要澄清的事情:您如何发布到索引控制器操作(AJAX、表单、其他)?
Save操作在做什么?它传递给视图的模型是什么? -
@Darin Dimitrov - 已更新信息。
-
@Darin Dimitrov - 我更新了我的帖子以展示我如何通过 Action 方法(在帖子之后)构建场景。所有这些数据在技术上都是场景的一部分......从数据的角度将其拆分是有意义的,因为有很多不同的数据。 (我的例子有点做作——我没有展示所有内容。)当我保存时,我只保存场景(现在应该包含所有数据信息)。这有帮助吗?
标签: asp.net-mvc-2