捕获控制器重定向操作并通过jquery / Ajax加载

时间:2015-04-07 11:09:16

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

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

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

<div></div>

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

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

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

例如,当我点击此视图中的提交时:

@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; }
    }
}

controllername public class TreeviewController:Controller

首页加载_NewEmpDetails&gt; _NewEmpSecond&gt; _NewEmpThird&gt; _NewEmpFourth

2 个答案:

答案 0 :(得分:0)

所以它可能会像这样。

@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>
}

注意:在Html.BeginForm中,我提到了ControllerName,请将其更改为您要写入StoreName操作的控制器名称。

这将在您的控制器中:

注意:我假设您的会话中存储了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中加载你的局部视图。

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

修改

根据您的评论我想要加载的_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.
}

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

答案 1 :(得分:0)

基本上,您无法为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);
                    }
                },
            });

        });