tags:

views:

17

answers:

1

I use my View to added a record in a database table. After I click submit, I want the screen to clear ready for my next insert. So within my controller I send a new ViewModel with the default values for both my HttpGet and HttpPost. However I am finding that once I have inserted a record, all the old values remain after my HttpPost. What am I doing wrong?

    [HttpGet]
    [Authorize(Roles = "Administrator, AdminAccounts")]
    public ActionResult Add()
    {
        ViewData["LastPerson"] = string.Empty;

        return View(new EmployeeViewModel()); 
    }

    [HttpPost]
    [Authorize(Roles = "Administrator, AdminAccounts")]
    public ActionResult Add(Employee employee)
    {
        if (ModelState.IsValid)
        {
            var employeeViewModel = new EmployeeViewModel();
            ViewData["LastPerson"] = string.Format("{0} {1} {2}", employee.Forename, employee.Middlenames,
                                    employee.Surname);
            employeeViewModel.Employee = employee;
            employeeViewModel.Employee.Add();
        }
        return View(new EmployeeViewModel());
    }

My view looks like this;

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/AdminAccounts.master" 
Inherits="System.Web.Mvc.ViewPage<SHP.WebUI.Models.EmployeeViewModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Add
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="AdminAccountsContent" runat="server">

    <% using (Html.BeginForm("Add", "Employee")) {%>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <legend>Add Employee</legend>
            <table>
                <tr>
                    <td align="right">
                <%: Html.LabelFor(model => model.Employee.UserName)%>
                   </td>                    
                    <td>
                <%: Html.EditorFor(model => model.Employee.UserName)%>
                <%: Html.ValidationMessageFor(model => model.Employee.UserName)%>
                    </td>
                </tr>
                <tr>
                    <td align="right">
                <%: Html.LabelFor(model => model.Division.DivisionId) %>
                   </td>                    
                    <td>
                <%: Html.DropDownListFor(model => model.Division.DivisionId, Model.DivisionSelectList, "<--Select-->")%>
                <%: Html.ValidationMessageFor(model => model.Division.DivisionId)%>
                    </td>
                </tr>
                <tr>
                    <td align="right">
                <%: Html.LabelFor(model => model.Department.DepartmentId) %>
                   </td>                    
                    <td>
                <%: Html.DropDownListFor(model => model.Department.DepartmentId, Model.DepartmentSelectList, "<--Select-->")%>
                <%: Html.ValidationMessageFor(model => model.Department.DepartmentId) %>
                    </td>
                </tr>

                <tr>
                    <td align="center" colspan="2" style="padding-top:20px;">
                    <input type="submit" value="Save" /></td>
                </tr>
            </table>
            <% if (ViewData["LastPerson"].ToString().Length > 0)
               { %>
                <p>
                   At time <% Response.Write(DateTime.Now.ToString("T")); %> 
                   - You have just entered <%Response.Write(ViewData["LastPerson"].ToString()); %>.
                </p>
             <%} %>
        </fieldset>

    <% } %>

    <div>
        <%: Html.ActionLink("Back to List", "Index") %>
    </div>

    <script language="javascript" type="text/javascript">

        //Hook onto the DivisionId list's onchange event
        $("#Division_DivisionId").change(function () {
            //build the request url
            var url = '<%: Url.Content("~/")%>' + "Employee/GetDepartments";
            //fire off the request, passing it the id which is the DivisionId's selected item value
            $.getJSON(url, { divisionId: $("#Division_DivisionId").val() }, function (data) {
                //Clear the Department list
                $("#Department_DepartmentId").empty();
                $("#Department_DepartmentId").append("<option><--Select--></option>");
                //Foreach Department in the list, add a department option from the data returned
                $.each(data, function (index, optionData) {
                    $("#Department_DepartmentId").append(
                    "<option value='" + optionData.DepartmentId + "'>" +
                        optionData.DepartmentName + "</option>");
                });
           });
        }).change();

    </script>
+2  A: 

ModelState can surprise you with the data it ends up remembering. However, in your case, you should just redirect to your blank page, rather than returning the View(model) directly:

return RedirectToAction("Add");

Instead of:

return View(new EmployeeViewModel());

After submitting the form, what happens if the user refreshes the browser? With your design, it will re-postback the form data, which isn't good. A redirect will solve that problem. See here for more info: http://en.wikipedia.org/wiki/Post/Redirect/Get.

Kirk Woll
@arame3333, just make `LastPerson` a query string argument and pass the value when you call RedirectToAction as a route value: `RedirectToAction("Add", new { lastPerson = ViewData["LastPerson"] });` Then you can consume that value in your other controller action `Add` by adding another parameter to it (preferably with a default value you your page works even if the value isn't set.)
Kirk Woll
Thank you for that, that is a better solution than the one I tried.
arame3333