1
votes

I started my first project with Core 2.0 Razor page, i just have small experience with MVC 5 before (previous projects are working fine).

The problem is simple with Razor pages and AJAX:

  • Have a page with list of customers

  • Link to edit the customer using AJAX to call the Razor partial page Customer_editPartial (it returns full customer form to a modal DIV in project)

The problem is how to render the partial page returned by the Ajax call? If i return from the customer_editPartial.cs a new json with text it is working, but impossible to display the partial page.

Thank you for your help.

Here the Page customers.cshtml

<script>
function editCustomer(id) {
    $.ajax({
        type: "GET",
        url: "Customer_editPartial?id=0",
        contentType: "application/json",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        dataType: "json",
        success: function (response) {
            AjaxCustomer_LoadSuccess(response);
        },
        failure: function (response) {
            alert('Customer content load failed.');
        }

    })
}

function AjaxCustomer_LoadSuccess(data) {
    $('#displayContent').html(data);
}
</script>
<a onclick="editCustomer(0);">Edit customer</a>
Here the ajax return<br />

Page Customer_editPartial.cshtml

@page
@model UGM_Web.Pages.AHadmin.Customer_editPartialModel
edit partial form

Here the Customer_editPartial.cs

       [ValidateAntiForgeryToken]
    public IActionResult OnGet(int? id)
    {
        return Page();
        //return new JsonResult("This is working when i return json text");

    }

    public void OnPost()
    {
    }
1
Can someone help me, please? - jcq

1 Answers

1
votes

The main answer was found with TechFisher in another post (How to return a PartialView from Core 2 RazorPage ViewModel Handler).

But at same time in my code i got error with ajax datatype (it was set to json instead of html :( Which of course cannot work to receive a partial view...). Also in the partial page 'Customer_editPartial.cshtml', you need to remove the '@page' directive.

Now in your razor pages to return a partial page you simply need to set a PartialViewresult object and return it:

     public IActionResult OnGet(int? id)
    {
        Customer_editPartialModel _model = new Customer_editPartialModel(_dbContext);
        var myViewData = new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(),
                                new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary());
        PartialViewResult _resultPartialPage = new PartialViewResult()
        {
            ViewName = "Customer_editPartial",
            ViewData = myViewData,
        };
        return _resultPartialPage;
    }

EDIT: A simpler solution

return new PartialViewResult() { ViewName = "Customer_editPartial", ViewData = this.ViewData };