ASP.NET MVC局部视图和表单操作名称

4
如何创建一个具有指定ID的表单的部分视图? 我已经做到了:
using (Html.BeginForm(?action?,"Candidate",FormMethod.Post,new {id="blah"}))

局部视图用于创建和编辑,因此第一个参数?action?将不同。我无法弄清楚?action?应该是什么值。


更新:

我想我的问题没有表述清楚。我最终做的是拆分Request.RawUrl以获取控制器名称和操作名称:

 string[] actionUrlParts = ViewContext.HttpContext.Request.RawUrl.Split('/');
 using (Html.BeginForm(actionUrlParts.Length >= 2? actionUrlParts[2] : "",
        actionUrlParts.Length >= 1 ? actionUrlParts[1] : "", FormMethod.Post, new { id = "blah" }))   

这种方法有点丑陋,但它可以工作。是否有更好的方法在局部视图中获取操作名称?

3个回答

7

通过ViewData传递要执行的操作。

在呈现视图的操作中,为回传操作创建一个ViewData项。在您的表单中引用此ViewData项以填充操作参数。或者,您可以创建一个仅用于视图的模型,其中包括操作和实际模型作为属性,并从那里引用它。

使用ViewData的示例:

using (Html.BeginForm( (string)ViewData["PostBackAction"], "Candidate", ... 

渲染操作:

public ActionResult Create()
{
     ViewData["PostBackAction"] = "New";
     ...
}


public ActionResult Edit( int id )
{
     ViewData["PostBackAction'] = "Update";
     ...
}

使用 Model 的示例

public class UpdateModel
{
     public string Action {get; set;}
     public Candidate CandidateModel { get; set; }
}

using (Html.BeginForm( Model.Action, "Candidate", ...

渲染操作:

public ActionResult Create()
{
     var model = new UpdateModel { Action = "New" };

     ...

     return View(model);
}


public ActionResult Edit( int id )
{
     var model = new UpdateModel { Action = "Update" };

     model.CandidateModel = ...find corresponding model from id...

     return View(model);
}
编辑: 根据您的评论,如果您认为这应该在视图中完成(尽管我不同意),则可以尝试一些基于ViewContext.RouteData的逻辑。
<%
    var action = "Create";
    if (this.ViewContext.RouteData.Values["action"] == "Edit")
    {
        action = "Update";
    }
    using (Html.BeginForm( action, "Candidate", ... 
    {
 %>

这个方法可以运行,但我不想改变控制器代码来处理视图应该能够解决的问题。 - Dmitriy Shvadskiy
我添加了另一种方法,这完全基于视图,但我认为控制哪个操作要回发到控制器是正确的位置。 - tvanfosson
是的,这正是我在寻找的。操作名称在ViewContext.RouteData.Values["action"]中。 - Dmitriy Shvadskiy
@Dmitriy -- 在示例中更新为使用values属性。我仍然认为控制器应该通过选择具有固定后台URL的视图或向具有动态后台URL的视图提供后台URL来控制应用程序中的流程。视图应负责呈现,而不是控制逻辑。 - tvanfosson
谢谢您提供的信息,它解决了我在将某些条件功能扩展到Partial时遇到的问题。关于使用ViewContext.RouteData的代码示例,我需要将其强制转换为字符串进行比较,如下所示,但这对我找到正确方向非常有帮助。 <%if ((string)this.ViewContext.RouteData.Values["action"] == "Create") {%> - 谢谢,Norman - Norman

1

将操作和控制器作为 null 传递。扩展将仅使用当前操作和当前控制器。

using (Html.BeginForm(null, null, FormMethod.Post, new { id="Model" }))

表单生成的操作与此局部视图的父视图相同。

它会生成:

<form action="/Orders/Edit/1" id="Model" method="post">

对于链接 http://localhost:1214/Orders/Edit/1

... 还有这个

<form action="/Orders/Create" id="Model" method="post">

针对URL http://localhost:1214/Orders/Create


0
<% html.RenderPartial("MyUserControl", Model.ID) %>

你好,请不要只发布代码答案,通过解释你的代码是如何解决问题的,以及它的工作原理,可以大大提高你的答案质量。 - Will Barnwell
仅提供代码的答案质量较低,可能会被删除。应该始终至少有一两个句子(最好是一个段落)来说明你正在回答的问题、假设、条件、陷阱等。 - Eric Leschinski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接