0

I have an action Create and method Save. The create action simply displays the view as shown below

public ActionResult Create()
        {
return view();
}

In create view, i get few fields like Name, Address etc. Once the user enters the data and click on the save button, i call the Save method using ajax call. In Save method, i am validating the data:

 [HttpPost]
            public bool Save(UserModel User)
            {
                if (ModelState.IsValid)
                {

                    // save the data
                     return true;
                }

                else
                {
                   return false; 
                }
            } 

the response of this method is used in ajax of Create View:

$(function () {
         $("#btnSave").click(function () {
                $.ajax({
                 type: "POST",
                 contentType: "application/json;charset=utf-8",
                 url: "/Contoller/Save",
                 data:
                            // parameters
                 async: false,
                 success: function (data_l) {
                     if (data_l == true)
                     {
                         alert("record has been saved in database");
                         window.location.href = "@Url.Action("Index","Controller")";
                     }
                     else{
                         alert ("Invalid Entry");
                         window.location.href = "@Url.Action("Create","Controller")";
                     }
                 },
                   error: function () {
                       console.log("there is some error");
                   }
             });
         });

What i want to achieve is based on the response from the Save method, i should perform two operation. If the data is properly validated, data is saved and index page is loaded back. If validation is failed, i want to display the create view with fields entered along with validation messages. I am sure that data annotation attributes are properly used in the model. Can someone please help me in solving this.

2
  • what is wrong with your current implementation? Commented Apr 28, 2014 at 9:51
  • I am unable to show the view with entered fields Commented Apr 28, 2014 at 9:53

1 Answer 1

1

I suggest you perform validation on server side i.e. in your controller. Perform input validation first, if all fine, save the data on persistent store. If the data is saved successfully load index view or list view (whichever view you want by either return View() or RedirectToResult()). If there are any problem add an error in the ModelState object and return the same view. At client the error will be displayed along with the data already entered by user.

For an example refer below code snippet (there might be other ways however this is what we use at the moment):

    public ActionResult AddNewSearch(SearchViewModel searchModel)
    {
        if (User.Identity.IsAuthenticated)
        {
            if (ModelState.IsValid)
            {
                var organizationUser = this.GetUser();

                if (organizationUser == null)
                {
                    ModelState.AddModelError("RecordNotFound", string.Format("No organization user found!!!"));
                    return RedirectToAction("LogOff", "Account");
                }

                if (this.searchService.GetUserSearch(organizationUser.Id, searchModel.Name) != null)
                {
                    ModelState.AddModelError("RecordAlreadyExists", string.Format("Search already exists!!!"));
                    return View(searchModel);
                }

                var userSearchDomainModel = mappingService.Map<SearchViewModel, Search>(searchModel);
                searchService.AddUserSearch(organizationUser, userSearchDomainModel);
                return RedirectToAction("Index", "Search");
            }
        }

        return RedirectToAction("Index", "Search");
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.