0

I am creating an CRUD Application in Asp.Net Core

After Add Operation I am redirecting to same view with setting model value as null to get another entry

Below is my code

public IActionResult Add(OptionMasterVM model)
    {
        try
        {
            model.QuestionList = context.QuestionMaster.Select(x => new SelectListItem { Text = x.QuestionName, Value = x.QuestionId.ToString() }).ToList();

            if (HttpContext.Request.Method == "POST")
            {
                OptionMaster _optionmaster = new OptionMaster();
                _optionmaster = model.OptionMaster;
                using (var ctx = new QuestionnaireEntities(_configuration))
                {
                    ctx.OptionMaster.Add(_optionmaster);
                    ctx.SaveChanges();
                }
                TempData["Msg"] = "Option Added Successfully , Add Another Option";
                model.OptionMaster.OptionValue = string.Empty;
                model.OptionMaster.OptionRating = 0;
                return View(model);
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex);
        }
        finally
        {
        }
        return View(model);
    }

Here I am setting Option Value to empty and rating to Zero to take next entry , but on view it does not show empty and zero , on view it show previously filled value.

enter image description here

After Setting below code these two fields should be reset but they don't

model.OptionMaster.OptionValue = string.Empty;
model.OptionMaster.OptionRating = 0;

Is there any other way to set model object as null in Asp.net Core ?

Tanwer
  • 1,503
  • 8
  • 26
  • 41
  • Is it Ajax request ? – lucky Mar 14 '18 at 08:47
  • 2
    You are not _redirecting to same view_ (to do that you would use `RedirectToAction()`). And to explain the behavior, refer [this answer](https://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111). If you want to display the view with a different model then follow the PRG pattern –  Mar 14 '18 at 08:48
  • "OptionMaster _optionmaster = new OptionMaster(); _optionmaster = model.OptionMaster;" - that makes no sense, too. Unnecessary object creation. – Fildor Mar 14 '18 at 09:02
  • @lucky no , its not Ajax request – Tanwer Mar 14 '18 at 09:04
  • @StephenMuecke , Thanks , All I need is ModelState.Clear() before resetting model object – Tanwer Mar 14 '18 at 09:05
  • @Fildor Thanks to you too , W – Tanwer Mar 14 '18 at 09:05
  • Do it properly by redirecting to a separate `[HttpGet]` method (which will not have a parameter for the model) –  Mar 14 '18 at 09:07
  • @StephenMuecke , That's complicated , having two actionMethod for one purpose – Tanwer Mar 14 '18 at 09:11
  • 1
    No it is not, and it the standard way –  Mar 14 '18 at 09:13
  • And you cannot get any client side or server side validation with your current implementation –  Mar 14 '18 at 09:15

2 Answers2

2

This can happen because Razor helpers use values from ModelState, rather than the model itself. Your OptionValue is probably displayed using a helper, for example:

@Html.TextBoxFor(m => m.OptionMaster.OptionValue)

When you change model values within an action, you need remove the old values from ModelState before rendering the View.

The easiest way of doing this is to call ModelState.Clear()

model.OptionMaster.OptionValue = string.Empty;
model.OptionMaster.OptionRating = 0;

ModelState.Clear();     // ensure these changes are rendered in the View

return View(model);
1

The values displayed for bound form fields come from ModelState, which is composed based on values from Request, ViewData/ViewBag, and finally Model. After posting, obviously, you'll have values set in Request, which will therefore be the values in ModelState. It works this way, so that when there's a validation error and the user is returned to the form to correct their mistakes, the values they posted will be there for them to edit.

Long and short, you need to follow the PRG (Post-Redirect-Get) pattern. Essentially, after posting, you only return the view on error. If the post is successful, you redirect. This not only clears ModelState, but also prevents accidental re-posts if the user attempts to refresh the page.

If you want to take the user back to the same view, simply redirect to the same action, but you need to do a redirect, not return the view.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444