Friday, October 12, 2012

Validate, Update data with asp.net MVC2

Lets see how to design the form for edit operation, we need to load data based on unique id (here ContactId) , and when updated data submitted to server we have to perform a validation if data looks good then we update else display the error message. so let's look at the html code of form tag


< % using (Ajax.BeginForm("EditClient", new AjaxOptions
               {
                   UpdateTargetId = "dvUpdateClient",
                   InsertionMode = InsertionMode.Replace,
                   OnBegin = "ajaxValidate",
                   OnSuccess = "getGbPostSuccess",
                   OnFailure = "showFaliure",
                   Confirm = "You sure you want to update this information?",
                   HttpMethod ="Post"
               }))
           {%>
        < %: Html.ValidationSummary(true) % >


As we have defined onBegin, OnSuccess, and OnFailure method in ajax, we have write some javascript methods with specified name, so this is how the script function will look like.


function ajaxValidate() {
            $get("dvResult").innerHTML = "Updating...";
            $get("btnUpdateClient").disabled = true;

        }

        function getGbPostSuccess(ajaxContext) {
            $get("dvResult").innerHTML = "Updated successfully";
            // $get("btnAddClient").disabled = false;
        }

        function showFaliure(ajaxContext) {
            $get("dvResult").innerHTML = "Update fail.";
            $get("btnUpdateClient").disabled = false;
        }


This is how we store the unique id in mvc2 form, this unique id is required to perform update operation in database. so the html code will look like
< %: Html.HiddenFor(model => model.ContactId) % >

now lets see some fields on the form that we need to validate & update, if validation fail it will display the inline error message.

Organisation Name : < %: Html.TextBoxFor(model => model.OrgName) %>
                            < %: Html.ValidationMessageFor(model => model.OrgName) %>
Remember  you must specify the following line of code before form tag , so the validation works properly.
  < % Html.EnableClientValidation(); %>

Now we see how to design the model where we can implement business validation as we need.


 public class ClientEdit
    {
        public long ContactId { get; set; }

        [Required(ErrorMessage = "Organisation name required.")]
        [DisplayName("Organisation Name")]
        public string OrgName { get; set; }
}


You must be thinking how the controller will look like, as there are two need on this form, one to load the data and second to update the data. so here is the code.

to load the data:

 public ActionResult EditClient(string ContactId)
        {
            object _contactId = ContactId as object;
            long clientId = Convert.ToInt64(_contactId);

            tbContact c = ClientService.GetClient(clientId);
            Models.ClientEdit ce = new ClientEdit()
            {
                ContactId = c.ContactId,
                OrgName = c.OrgName
             
            };

            return View(ce);
        }

to update the data:


        [HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditClient(ClientEdit clnt)
        {
            tbContact updateContact = null;

            if (Request.IsAjaxRequest())
            {
                if (ModelState.IsValid)
                {
                    clnt.UpdateDate = DateTime.Now;

                    tbContact c = new tbContact()
                    {
                        ContactId = clnt.ContactId,
                        OrgName = clnt.OrgName                     

                    };

                    updateContact = ClientService.UpdateClient(c);

                    if (updateContact != null)
                    {
                        return RedirectToAction("ResultClient", "Client", new { action = "?action=ClientUpdated" });
                    }
                }

            }

            return View(updateContact);
        }


So we are done ! Hope you find this helpful.

No comments: