Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC return View with new Instance of Model instead of using Redirect To Action

I have a form view which uses a ViewModel. A new view is rendered by Action "New". When this form is submitted I send back the info to action "Add".

If all actions on DB are successful I want to refresh the view. I create a new instance of viewmodel from inside "Add" action and do return View("New",viewModel) . This does not refresh my view. All old values ( that were submitted) remains in the view. Is there a way to refresh the page without RedirectToAction method.

I read on another post that ModelState.Clear should not be used as it can have undesirable result.

Thank you,

Mar

Edit 1 - Code Added

New

 public ActionResult New(string id)
        {
            var sysId= new Guid(id);
.......
........

  string Details = pDto.Name + "(" + pDto.Code + ")";

            var vm= new ViewModel(id);
            vm.Details = Details;

            return View(vm);
        }



 public ActionResult Add(ViewModel vm)
        {
                        ViewModel vm= vm;

            if (ModelState.IsValid)
            {

                              var dto= _qRepository.GetFeaturesBy(viewModel.Code);

                if (dto!= null)
                {

                    ModelState.AddModelError("Code", "Code is already in Use.");

                    return View("New", viewModel);
                }

                _productService.AddFeature(..........);
               // ModelState.Clear();  -- this works          
                vm= new ViewModel(vm.pId) { Message = "Code" + viewModel.Code + " was added ......", Details = vm.Details };

            }


          return  View ("New", vm);

        }
like image 319
TheMar Avatar asked Jan 06 '11 21:01

TheMar


1 Answers

You should try to adhere to the post-redirect-get pattern. The only time you don't is when the post failed and you want to return the validation errors so the client can re-post the form. This is what happens when you return a view from a post action method. All those form values are still floating about in ModelState waiting to be used again on the form.

You can use RedirectToAction("New") if you want to let user add another item right away. Also, it sounds like both actions should be named New and then decorate the post version with an [HttpPost] attribute and the PostModel parameter. Things get messy if you post and get between two different actions because then you'd have to remember to explicitly set the action on the html form and also to return the right view on validation failure.

like image 92
dotjoe Avatar answered Nov 15 '22 07:11

dotjoe