-1

In my MVC project I tried to render partial views with ajax but I'm not able to create the Routing in it. how can one implement routing in an ajax based partial view.

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

My View

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

my route is not shown when I click on the category button. it only shows the base url and the # sometime if button is clicked. how can i show the route and not refresh the page. I know using angular or any framework its easy to implement but how can we do that using just asp.net mvc .

This usually happens on my edit and create page my edit method is

 [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); ;
        }

When I enable attribute routing it stops calling my Controller method.

Dummy
  • 255
  • 1
  • 4
  • 14
  • What do you mean _my route is not shown_? What are you expecting. And what does your `Edit()` method have to do with the question - your not calling that anywhere in the code you have shown. –  Jul 25 '17 at 04:58
  • your Edit(int? id) action takes nullable integer as parameter. then why in the post call you are trying to pass all data of the form "data: $("#frmAddEditCategory").serialize()," ? you are trying to call "SaveCategory" action inside "Category" controller. but you are showing "Edit" action to us. Why? – Chandan Kumar Jul 25 '17 at 05:01
  • I can't find any method that call `Edit` action method in view page. Also you're trying to pass serialized data (i.e. query string) but your POST method accepts only `Nullable`. Note that `RouteAttribute` more often used for GET or redirect rather than POST method. – Tetsuya Yamamoto Jul 25 '17 at 05:03
  • I guess he needs to implement routing manually after each ajax call something like this windows.location.href = "https://localhost/Category/Edit/5". – touseefkhan4pk Jul 26 '17 at 14:41
  • Anyone with better solution, kindly share here – touseefkhan4pk Jul 26 '17 at 14:42

1 Answers1

-1

There is issue in your AJAX call. You are creating URL wrong way. Please replace URL part like this.

Declare your URL in your View like this and use this variable in AJAX call.

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

$.ajax({
     url: categoryUrl ,
     type: "post",
     data: $("#frmAddEditCategory").serialize(),
     success: function (data) {
        debugger;
        ('#main-content').html(data);
      },
Pang
  • 9,564
  • 146
  • 81
  • 122
Dilip Oganiya
  • 1,504
  • 12
  • 20