【问题标题】:Capture controller redirect action and load through jquery/Ajax捕获控制器重定向操作并通过 jquery/Ajax 加载
【发布时间】:2015-06-11 23:09:33
【问题描述】:

在我的布局页面中,我有这个:

<div class="containerSidebar">
    <div class="SidebarSection">
        @RenderBody()
    </div>
</div>

<div></div>

<div id="detailView"></div>

当我点击侧边栏中的链接时,它们会在 detailView 部分中打开。

当我单击详细视图中的提交按钮时,它会在渲染主体部分中打开,但我希望它继续在详细视图部分中打开。

例如,当我从该视图单击提交时:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>TestEmployee</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Forename, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Forename, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Forename, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Surname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Surname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>

它将转到控制器中的此部分:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult _NewEmpDetails([Bind(Include = "ID, Forename, Surname")] First NewEmpFirst)
{
    if (ModelState.IsValid)
    {
        var sessionValues = new MySessionValues();
        sessionValues.Employee = NewEmpFirst;
        Session["MySessionValues"] = sessionValues;
    }

    return RedirectToAction("_NewEmpSecond");
}

我希望它直接到达 RedirectToAction 部分和 _Layout 页面中的 Jquery 或 Ajax 代码以捕获 _NewEmp... 并再次将其动态加载到 detaiView 部分中。

所以从 _Layout 页面调用的 jquery 文件中的类似内容

 $("#detailView").submit(function () {
            var form = $(this);
            $.ajax({
                type: "GET",
                url: form.attr('RedirectToAction'),
                success: function (data) {
                    //At this point I would like to redirect
                    $("#detailView").load($(this).attr("href"));
                },
            });

        });

我真的很陌生,所以如果有人能提供帮助,那将非常感谢!

型号:

namespace OrwellFrontEnd.NewEmp
{
    public class First
    {
        public int ID { get; set; }        
        public string Forename { get; set; }        
        public string Surname { get; set; }       

    }

    public class Second
    {
        public int ID { get; set; }
        public string Department { get; set; }
    }

    public class FirstSecond
    {
        public int ID { get; set; }
        public string Forename { get; set; }
        public string Surname { get; set; }
        public string Department { get; set; }
    }

    public class Third
    {
        public int ID { get; set; }
        public string Title { get; set; }
    }

    public class Fourth
    {
        public int ID { get; set; }
        public bool FullTime { get; set; }
    }
}

控制器名称公共类 TreeviewController : 控制器

要加载的第一页 _NewEmpDetails > _NewEmpSecond > _NewEmpThird > _NewEmpFourth

【问题讨论】:

  • 首先div 不会有提交操作,而form 会有。如果您对JsonResult 有一点了解,那么您可以做到这一点。
  • 表单提交正常吗?唯一的问题是我无法在局部区域中打开下一个局部视图。
  • 提交是因为您的input type = submit。要加载不同的局部视图,您需要大量修改代码。请提供更多详细信息,我可能会对您有所帮助。
  • 它加载了正确的局部视图,唯一的问题是它在布局页面的 renderbody 部分中将其加载为完整视图,因为我想停止该操作并将其加载到 detailView 部分中像这样: $("#detailView").load($(this).attr("href"));哪些信息/代码最能帮助您?我很乐意提供。寻找允许提交的东西,更新会话变量,然后捕获要加载的部分视图并将其加载到详细视图部分
  • 您没有取消标准提交。如图所示,您的代码将执行 ajax 调用,然后立即执行标准提交和重定向。

标签: jquery ajax asp.net-mvc asp.net-mvc-5


【解决方案1】:

所以它可能会这样。

@using (Html.BeginForm("StoreName","TreeviewController",FormMethod.Post, new {id="frmStoreDetails"}))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>TestEmployee</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Forename, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Forename, new { htmlAttributes = new { @class = "form-control", id="txtForeName" } })
                @Html.ValidationMessageFor(model => model.Forename, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Surname, new { htmlAttributes = new { @class = "form-control", id="txtSurName" } })
                @Html.ValidationMessageFor(model => model.Surname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" onclick="javascript:SubmitForm();" class="btn btn-default" />
            </div>
        </div>
    </div>
}

注意:在我提到的ControllerName的Html.BeginForm中,请将其更改为您要写入StoreNameAction的任何controllerName。

这将在您的控制器中:

注意:我假设在您的会话中,您在模型中存储 FirstName 和 LastName 等,假设您的模型将包含 FirstName 和 LastName 属性,我将绑定 FirstName 和 LastName 并发送它通过 ajax 到您的 JsonResult 操作

[HttpPost]
public JsonResult StoreName(UserDataModel model)
{
     bool valid=false; //Just for safety check
    if(ModelState.IsValid)
    {
        var sessionValues = new MySessionValues();
        sessionValues.Employee = model.FirstName;
        Session["MySessionValues"] = sessionValues;
        valid=true;
    }
    return Json(new {result=valid});
}

用js编写表单提交如下:

function SubmitForm()
{
      var valid=false;
      $("#frmStoreDetails").on("submit",function(e){
            e.preventDefault();

            if($("#txtForeName").val()!="" && $("#txtSurName").val()!="")//Validation
            {
                 valid=true;
            }
            if(valid)
            {
                   model : {
                         'FirstName':$("#txtForeName").val(),
                         'LastName':$("#txtSurName").val()

                   };
                   $.ajax({
                       url:'/TreeviewController/StoreName',
                       type: 'POST',
                       dataType:'JSON',
                       contentType: "application/json; charset=utf-8",
                       data:JSON.stringify(model),
                       success:function(data){
                              if(data.result)
                              {
                                  $('#detailView').load("/TreeviewController/GetNewEmpSecond");
                              }
                              else
                              { 
                                  //display Error in some div
                              }
                       },
                       error:function(data){
                              //display error
                       }
                  });
            }
            $("#" + form).unbind('submit');
            return false;
      });
}

在您的控制器中再写一个PartialViewResult 动作,名称为GetNewEmpSecond,如下所示

[HttpGet]
public PartialViewResult GetNewEmpSecond()
{
        //do whatever you want here
        return PartialView('_NewEmpSecond');
}

就是这样。它会在指定的 div 中加载你的局部视图。

如果有任何疑问,请告诉我。

编辑:

根据您的 cmets 我接下来要加载的 _NewEmpSeconed 使用模型 @model OrwellFrontEnd.NewEmp.Second 我相信您需要将模型传回调用局部视图,这就是为什么您正在得到那个例外。所以只需在GetNewEmpSecond() PartialViewResult Action 中进行更改,如下所示"

[HttpGet]
public PartialViewResult GetNewEmpSecond()
{
        //do whatever you want here
        OrwellFrontEnd.NewEmp.Second model = new OrwellFrontEnd.NewEmp.Second();

        //Fill model values
        return PartialView('_NewEmpSecond',model); //Send your model with partial view. I hope you are receiving it in the Partial View.
}

注意:我已按照您的要求更改了控制器名称。 关于您的进一步步骤,您可以按照相同的过程加载其他部分视图。希望它被清除。

【讨论】:

  • 您好,非常感谢。我收到 Ajax 部分的无效模型消息。我接下来要加载的 _NewEmpSeconed 使用模型 @model OrwellFrontEnd.NewEmp.Second 这就是我使用会话变量的原因。抱歉,我没有包括在内。我加载了大量的局部视图,每个视图都有自己的模型来构建一个数据集,然后插入到一个数据库中,拆分成它们自己的表
  • return PartialView('_NewEmpSecond',model); -“在字符文字中返回太多字符”如何将值从 Ajax 脚本传递回下一个视图以存储在会话变量中?有没有办法只更新 Ajax 脚本中的会话变量,因为我不想经历多个阶段?
  • 您能否发布异常的屏幕截图...关于您的第二个问题,如果您查看我给出的答案,您可以看到我已经通过 Ajax 将模型值传递给控制器​​...同样的方式您可以实现其他部分视图。
【解决方案2】:

基本上,您无法为 Ajax 请求执行 Response.Redirect。但是您可以通知请求者从新的 url 重新加载。因此,在控制器操作方法中更改以下代码对您的代码有意义

public ActionResult ActionName(Type model)
{
  //do something
  //return RedirectToAction("_NewEmpSecond");// not possible
  return Json(new{status='success', redirectUrl='/Action2/Param1'})
}

同时重构你的 ajax 调用

$("#detailView").submit(function (e) {
            e.preventDefault();// do not perform default submit of form
            var form = $(this);
            $.ajax({
                type: " ",
                url: form.attr('RedirectToAction'),
                success: function (data) {
                   if(data.status==='success'){
                    //At this point I would like to redirect
                     $("#detailView").load(data.redirectUrl);
                    }
                },
            });

        });

【讨论】:

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