【问题标题】:MVC3 ASP.NET Can I reload my view when validating a form nested within a partial view?MVC3 ASP.NET 验证嵌套在局部视图中的表单时,我可以重新加载我的视图吗?
【发布时间】:2012-07-31 01:03:20
【问题描述】:

我有一个局部视图,我在索引页上使用它来显示表单。当从索引页面上的下拉菜单中选择一个项目时,部分视图将加载相应的表单数据。我需要在提交时验证表单,但我不确定从我的控制器返回什么会在显示错误时正确加载页面。我的提交按钮目前在我的部分视图中。 (我尝试将提交移动到索引页面,但它没有从表单返回任何内容。)如果存在验证错误,则部分视图会加载,但索引视图的下拉菜单不会。我已经看到了这个问题的一些解决方案,但没有一个在这种情况下有效,可能是由于下拉菜单。任何帮助是极大的赞赏。请让我知道 HTML 是否有帮助,我在为这篇文章格式化它时遇到问题。

控制器:

public class PrinterSettingsController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Areas = db.Areas.ToList();
        PopulateDocumentTypeViewBag();
        return View();
    }

    public ActionResult AreaDocumentSettingsList(int areaId = 0)
    {
        PopulateDocumentTypeViewBag();

        //get area, contains list of document settings
        }

        return PartialView("_AreaDocumentSettingsList", selectedArea);
    }

    [HttpPost]
    public ActionResult AreaDocumentSettingsList(Area selectedArea)
    {

        if (IsPrinterValid(selectedArea.PrinterName) == false)
        {
            ModelState.AddModelError(string.Empty, "Incorrect printer path entered.");
        }

        if (ModelState.IsValid)
        {

            //do some stuff, save the new records to the database

            db.Entry(originalAreaRecord).CurrentValues.SetValues(selectedArea);
            db.SaveChanges();

            //if everything saves fine, go to a different page
        return RedirectToAction("Index", "Workorder");

        }
        //if there are errors -- this part needs to be changed -- show errors in partial view, but also display view it's nested inside of

        return View("_AreaDocumentSettingsList", selectedArea);

    }

【问题讨论】:

  • 那么您要问的是如何在提交部分视图(您的表单)时刷新索引?
  • @cshemby 是的,现在当页面加载时出现验证错误,索引页面上的任何内容都不会出现
  • 看看这个演练。它比您需要的要复杂一些,但应该很好地解释如何传递部分视图。 geekswithblogs.net/blachniet/archive/2011/08/03/…

标签: asp.net asp.net-mvc-3 partial-views


【解决方案1】:

@cshemby 的链接很有帮助:Updating Partial Views with Unobtrusive AJAX in MVC 3

但我的问题最终是我将部分视图加载到带有 javascript .changed 事件的 <div> 标记中。为了解决这个问题,我在局部视图的索引页面中添加了一个@Html.RenderPartial,并将下拉列表的值传递回我的控制器。这样我就可以重新加载整个页面,包括验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多