【问题标题】:Routing with MVC partial Views using ajax使用 ajax 使用 MVC 部分视图进行路由
【发布时间】:2017-07-25 04:53:32
【问题描述】:

在我的 MVC 项目中,我尝试使用 ajax 渲染部分视图,但我无法在其中创建路由。如何在基于 ajax 的局部视图中实现路由。

 public ActionResult ViewResult(string view, object viewModel)
    {
        if (Request.IsAjaxRequest())
        {
            return PartialView(view, viewModel);
        }
        return View(view, viewModel);
    }

我的观点

    <div class="row">

    <div class="x_panel">
        <div class="x_title">
            Category
        </div>
        <div class="x_content">
            <form method="post" id="frmAddEditCategory" data-parsley-validate class="form-horizontal form-label-left">
                <div class="form-horizontal">
                    @Html.HiddenFor(model => model.CategoryID, new { @id = "hdnCategoryId" })
                    @Html.ValidationSummary(true)
                    <div class="form-group">
                        @Html.LabelFor(model => model.CategoryName, new { @class = "control-label col-md-2" })
                        <div class="col-md-4">
                            @Html.TextBoxFor(model => model.CategoryName, new { @class = "form-control", @id = "txtCategoryName" })
                            @Html.ValidationMessageFor(model => model.CategoryName)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Description, new { @class = "control-label col-md-2" })
                        <div class="col-md-4">
                            @Html.TextBoxFor(model => model.Description, new { @class = "form-control", @id = "txtDescription" })
                            @Html.ValidationMessageFor(model => model.Description)
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-2">   </div>
                        <div class="col-md-4">
                            <a id="btnSaveCategory" class="btn btn-primary btn-saveCategory" name="btnSave">Save</a>
                            <a id="btnCancel" class="btn btn-white btn-cancelCategory" name="btnCancel">Cancel</a>
                        </div>
                    </div>
                </div>
            </form>
</div>
</div>
</div>
<script>
    $(document).ready(function () {
        debugger;
        $("#btnSaveCategory").click(function () {
            debugger;
            $("#frmAddEditCategory").removeData("validator");
            $("#frmAddEditCategory").removeData("unobtrusiveValidation");
            $.validator.unobtrusive.parse("#frmAddEditCategory");
            if ($("#frmAddEditCategory").valid()) {
                $.ajax({
                    url: "@Url.Action("SaveCategory", "Category")",
                    type: "post",
                    data: $("#frmAddEditCategory").serialize(),
                    success: function (data) {
                        debugger;
                        $('#main-content').html(data);
                },
                error: function (a,b,c) {
                    $('#main-content').html('there is error while submit');
                }
            });
        }
        });

    $("#btnCancel").click(function () {
        $('#main-content').load("@Url.Action("Index", "Category")");
    });
    });
</script>

当我单击类别按钮时,我的路线未显示。它只显示基本 url 和 # sometime if 按钮被点击。我怎样才能显示路线而不刷新页面。我知道使用 angular 或任何框架很容易实现,但是我们如何仅使用 asp.net mvc 来做到这一点。

这通常发生在我的编辑和创建页面上 我的编辑方法是

 [HttpPost]
        //[Route("CategoryEdit/{id}/Edit")]
        //[Route("CategoryEdit/{id}")]
        //[Route("CategoryEdit/{id:range(1, 3)}")]
        // GET: /Category/Edit/5
        public ActionResult Edit(int? id)
        {
            var category = categoryService.GetCategory(id.Value);
            return ViewResult("_CategoryAddEdit", category); ;
        }

当我启用属性路由时,它会停止调用我的 Controller 方法。

【问题讨论】:

  • 什么意思我的路线没有显示?你在期待什么。你的Edit() 方法与这个问题有什么关系——你没有在你显示的代码中的任何地方调用它。
  • 您的 Edit(int? id) 操作将可空整数作为参数。那么为什么在 post call 中你试图传递形式为 "data: $("#frmAddEditCategory").serialize()," 的所有数据?您正在尝试在“类别”控制器中调用“保存类别”操作。但是您正在向我们显示“编辑”操作。为什么?
  • 我在视图页面中找不到任何调用Edit 操作方法的方法。此外,您正在尝试传递序列化数据(即查询字符串),但您的 POST 方法仅接受 Nullable&lt;int&gt;。请注意,RouteAttribute 更常用于 GET 或重定向而不是 POST 方法。
  • 我猜他需要在每次 ajax 调用后手动实现路由,例如 windows.location.href = "localhost/Category/Edit/5"。
  • 谁有更好的解决方案,请在这里分享

标签: c# jquery .net ajax asp.net-mvc


【解决方案1】:

您的 AJAX 调用存在问题。您正在以错误的方式创建 URL。请 像这样替换 URL 部分。

像这样在你的视图中声明你的 URL 并在 AJAX 调用中使用这个变量。

var categoryUrl = '@Url.Action("SaveCategory", "Category")',

$.ajax({
     url: categoryUrl ,
     type: "post",
     data: $("#frmAddEditCategory").serialize(),
     success: function (data) {
        debugger;
        ('#main-content').html(data);
      },

【讨论】:

  • OP 生成 url 的代码没问题。不需要声明单独的变量(这与问题无关)
  • 你检查了吗?
  • 您同意可以通过这种方式从 Jquery 调用:var categoryUrl = '@Url.Action("SaveCategory", "Category")',
  • 只是你不能这样称呼我所说的
  • 是的,您可以,但您不必这样做。我建议您在将来发布之前测试您的代码
猜你喜欢
  • 2011-06-29
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多