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

时间:2009-04-08 19:58:24

标签: asp.net-mvc

如何创建具有指定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 个答案:

答案 0 :(得分:7)

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

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

使用ViewData的示例:

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

渲染动作:

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


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

使用模型的示例

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", ... 
    {
 %>

答案 1 :(得分:1)

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

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

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

生成

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

for url http://localhost:1214/Orders/Edit/1

......还有这个

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

for url http://localhost:1214/Orders/Create

答案 2 :(得分:0)

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