Home > Software design >  .Net 6 Razor View Not Updating after Post
.Net 6 Razor View Not Updating after Post

Time:04-27

I am passing a complex model to a Razor View. The data in the model is used in a for-each loop in the view to display a list of products that are for sale in bootstrap cards. There are no forms on the view.

On the left side of the page are list elements that contain nested list elements. These represent product categories. When the user selects a category, I pass the product category to an action method in the controller as an integer. This will build a new model based on the selected category. The new model is then passed back to the view.

At this point, I want to display the categories that are in the category that the user selected. But, the view is not updating even though the model is now different.

I have been reading about this issue, and one forum post I read suggested that this is by design. I read somewhere that in order to achieve what I need to achieve, I have to clear the model state. But I cannot clear the model state because I am not passing the model back to the controller, and you can only pass the model back to the controller by reconstructing the model to be passed in an ajax call for example. I spent all day yesterday trying to get ajax to work and every time I executed the post, the model was populated in the JavaScript function and null or empty in the controller.

Is there another way to force the view to update upon sending a new model to the view? Does anyone have any suggestions?

<script type="text/javascript">


    function AddSubCategory(elem) {
        event.stopPropagation();

        var e = document.querySelectorAll(".products");

        e.forEach(box => {
            box.remove();
        });

        var categoryId= $(elem).data('sub-id');

        console.log(`Id: ${categoryId}`);

        var request;
        if (window.XMLHttpRequest) {

            request = new XMLHttpRequest();
        }       

        if (request != null) {
            var url = `/Products/GetProductsByCategory?categoryId=${categoryId}`;
            request.open("POST", url, false);
        };

            //request.onreadystatechange = function () {
            //  if (request.readyState == 4 && request.status == 200) {

            //  }
            //};

            request.send(); 

    //  model = JSON.stringify(model);

    //  console.log(model);

    //  $.ajax({
    //  type: "Post",
    //  url: '@Url.Action("GetProductsByCategory", "Products")',
    //  data: JSON.stringify({"categoryId": categoryId}),
    //  contentType: 'charset=utf-8;application/json',
    //  cache: false,
    //  complete: function (data) {
    //  }
    //});


    }

// Load all products
public async Task<IActionResult> Index()
{
    ReadCartIDFromCookie();

    string SubDomain = GetSubDomain(HttpContext);
    var allProducts = await _productService.GetAllProductsWithImagesAsync(SubDomain);

    var productCategoryLookup = await _productService.GetAllProductCategoryLookupAsync();

    ViewBag.host = SubDomain;
    ViewBag.productCategoryLookup = productCategoryLookup;

    return View("Index", allProducts);
}

//Load filtered list of products
[HttpPost]
public async Task<IActionResult> GetProductsByCategory(int categoryId = -1)
{            
    ReadCartIDFromCookie();

    string SubDomain = GetSubDomain(HttpContext);
    var allProducts = await _productService.GetAllProductsWithImagesAsync(SubDomain, categoryId);

    var productCategoryLookup = await _productService.GetAllProductCategoryLookupAsync();

    ViewBag.host = SubDomain;
    ViewBag.productCategoryLookup = productCategoryLookup;    
    
    return View("Index", allProducts);
}

CodePudding user response:

I was able to resolve my issue thanks to this post: https://stackoverflow.com/a/66277911/1561777

I did have a bit of trouble trying to figure it out because it was not completely clear, but I could tell it was what I needed to do. I ended up utilizing a partial view for the display of my products. Here is my final code.

//My index.cshtml razor view
<div  id="product"></div>//partial view will be loaded onto this div

//Javascript function that gets the chosen filter category Id
@section Scripts
{
<script type="text/javascript">

    function AddSubCategory(elem) {
        event.stopPropagation();
        
        //get the id
        var categoryId= $(elem).data('sub-id');

        console.log(`Id: ${categoryId}`);

        //call controller Products, controller action GetProductsByCategory and pass the categoryId
        //The partial view will be returned and load onto the div id #product
        $('#product').load(`/Products/GetProductsByCategory?categoryId=${categoryId}`);

    }

//when the index view first loads, load all products (i.e. category -1)     
$('#product').load(`/Products/GetProductsByCategory`);
        
</script>
}

public async Task<IActionResult> GetProductsByCategory(int categoryId = -1)
{            
    ReadCartIDFromCookie();

    string SubDomain = GetSubDomain(HttpContext);
    var allProducts = await _productService.GetAllProductsWithImagesAsync(SubDomain, categoryId);

    var productCategoryLookup = await _productService.GetAllProductCategoryLookupAsync();

    ViewBag.host = SubDomain;
    ViewBag.productCategoryLookup = productCategoryLookup;

    
//notice that I am using PartialView method
//Returning View was including the full website (i.e. header and footer).
//_Products is my partial view. allProducts is the 
//view model that is being passed to the partial view.
    return PartialView("_Products", allProducts);
}

Now, everytime I select a new category, the partial view is reloaded. Also, when first loading the view, all products are displayed as expected.

  • Related