加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC局部视图和表单动作名称

发布时间:2020-12-16 06:35:08 所属栏目:asp.Net 来源:网络整理
导读:如何创建具有指定ID的表单的部分视图? 我得到了: using (Html.BeginForm(?action?,"Candidate",FormMethod.Post,new {id="blah"})) 部分视图用于创建和编辑所以第一个参数?action?会有所不同.我无法弄清楚什么价值?行动?应该是. 更新: 我想我对这个问
如何创建具有指定ID的表单的部分视图?
我得到了:

using (Html.BeginForm(?action?,"Candidate",FormMethod.Post,new {id="blah"}))

部分视图用于创建和编辑所以第一个参数?action?会有所不同.我无法弄清楚什么价值?行动?应该是.

更新:

我想我对这个问题不够清楚.我最终做的是拆分Request.RawUrl以获取控制器名称和操作名称:

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

有点丑,但它有效.有没有更好的方法在局部视图中获取操作名称?

解决方法

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

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

使用ViewData的示例:

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

渲染动作:

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,...

渲染动作:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读