【问题标题】:MVC 3 - Posting partial view to a chosen controllerMVC 3 - 将部分视图发布到选定的控制器
【发布时间】:2010-12-01 19:43:15
【问题描述】:

我正在尝试学习来自 ASP.NET 背景的 MVC 3 和 Razor。

我想要获得一个简单的局部视图(在共享文件夹中)以发布到特定控制器,以便我可以在其他地方重复使用它,例如文章、博客等。我尝试使用以下变体。

@using (Html.BeginForm("Create", "Comment", FormMethod.Post,  new { }))
{
    <div>
        <fieldset>
            <legend>Comments</legend>

            <div >
                @Html.LabelFor(m => m.Name)
                @Html.TextBoxFor(m => m.Name)              
            </div>

            <div >
                @Html.LabelFor(m => m.Email)
                @Html.TextBoxFor(m => m.Email)              
            </div>

            <div >
                @Html.LabelFor(m => m.Body)
                @Html.TextBoxFor(m => m.Body)              
            </div>

            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    </div>
}

这不会发布到 cmets 控制器操作 Create,如下所示。

[HttpPost]
public ActionResult Create()
{
    // Save comment code here

    return View();
}

有什么简单的方法可以做到这一点而不必绑定到特定的路线?

【问题讨论】:

  • 生成的表单的 HTML 源代码是什么样的?单击提交按钮时会发生什么?
  • @mcl 感谢您的评论。当我单击提交按钮时,URL 更改为 /Comment/Create,并且在“/MVC3PartialView”应用程序中出现错误服务器错误。我希望 URL 保持不变并发回评论控制器。你知道有什么方法可以做到这一点吗?也许 ajax 会解决这个问题?
  • 我认为如果没有 ajax,你想要的不太可能,因为纯 HTTP 认为你想将表单发布到 /Comment/Create。我的猜测是你上面的部分被称为“创建”?这意味着它很可能也不能用作操作的视图。您的创建视图需要是简单的(但是是完整的页面),例如“感谢 cmets”(并且使用隐藏的表单输入,您可以获得此视图以提供返回文章的链接)。
  • 是的,你的权利我认为 ajax 是要走的路。我几乎得到它的工作原来是一个路由问题。我有地图路线(对于 CMS)routes.MapRoute(null, "{*slug}", new { controller = "Page", action = "Index", slug = UrlParameter.Optional });始终路由回同一个控制器。我需要找到一条适用于 CMS 以及在部分中发布表单的路线,这可能是另一个问题......感谢您的帮助。

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


【解决方案1】:

我找到了答案。

@using (Ajax.BeginForm("Create", "Comment",  new AjaxOptions() {
        UpdateTargetId = "MainContainer"    })) 
{ 
     <div>
        <fieldset>
            <legend>Comments</legend>

            <div >
                @Html.LabelFor(m => m.Name)
                @Html.TextBoxFor(m => m.Name)              
            </div>

            <div >
                @Html.LabelFor(m => m.Email)
                @Html.TextBoxFor(m => m.Email)              
            </div>

            <div >
                @Html.LabelFor(m => m.Body)
                @Html.TextBoxFor(m => m.Body)              
            </div>

            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    </div>
}

这使用 ajax 回发并且不会更改 URL。或者你可以使用 JQuery http://jvance.com/blog/2010/02/20/MakingAnAjaxFormWithJQueryInASPdotNETMVC.xhtml

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 2018-04-02
    • 2019-04-18
    相关资源
    最近更新 更多