Search code examples
c#asp.net-mvchttp-posthttp-getredirecttoaction

ASp.MVC HTTP Post not redirecting to action


I have 2 index methods in my controller, one of them is a GET and the other is a POST which is used on a form on the page.

When I submit my form, when the page refreshes, it shows a blank page instead of running through my GET index method and ideally reload that page.

POST METHOD

    [HttpPost]
    public void Index(ProductViewModel product)
    {
        try
        {
            var productContract = Mapper.Map<ProductViewModel, ProductContract>(product);
            _productService.CreateProduct(productContract);
        }
        catch (Exception ex)
        {

            throw ex;
        }
        RedirectToAction("Index");
    }

GET METHOD

    [HttpGet]
    public ViewResult Index()
    {
        _productService = new ProductServiceClient();
        var brandSerice = new ProductBrandServiceClient();
        var categoryService = new ProductCategoryServiceClient();

        var productPageViewModel = new ProductPageViewModel();
        var productViewModelList = new List<ProductViewModel>();
        var productBrandsViewModelList = new List<ProductBrandViewModel>();
        var productCategoriesViewModelList = new List<ProductCategoryViewModel>();

        try
        {
            productViewModelList.AddRange(_productService.GetProducts().Select(Mapper.Map<ProductContract, ProductViewModel>));
            productBrandsViewModelList.AddRange(brandSerice.GetProductBrands().Select(Mapper.Map<ProductBrandContract, ProductBrandViewModel>));
            productCategoriesViewModelList.AddRange(categoryService.GetProductCategories().Select(Mapper.Map<ProductCategoryContract, ProductCategoryViewModel>));

            productPageViewModel.ProductList = productViewModelList;

            productPageViewModel.ProductBrands = new SelectList(productBrandsViewModelList, "Id", "Description");
            productPageViewModel.ProductCategories = new SelectList(productCategoriesViewModelList, "Id", "Description");

        }
        catch (Exception ex)
        {
            throw ex;
        }

        return View(productPageViewModel);
    }

Solution

  • You need to return a result:

    [HttpPost]
    public ActionResult Index(ProductViewModel product)
    {
        // ...
    
        return RedirectToAction("Index");
    }