MyContactBook : Part 6 - Create Page for Edit existing Contact

Steps :
Step-1: Add new action into your controller for Get form (get Method) for Edit Contact.

Here I have added "Edit" Action into "Home" Controller. Please write this following code for the Action

            public ActionResult Edit(int id)
            {
                // Fetch Contact
                Contact c = null;
                c = GetContact(id); // GetContact I have created in the previous part

                if (c == null)
                {
                    return HttpNotFound("Contact Not Found!");
                }
                // Fetch Country & State
                List<Country> allCountry = new List<Country>();
                List<State> states = new List<State>();
                using (MyContactBookEntities dc = new MyContactBookEntities())
                {
                    allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
                    states = dc.States.Where(a => a.CountryID.Equals(c.CountryID)).OrderBy(a => a.StateName).ToList();
                }
                ViewBag.Country = new SelectList(allCountry, "CountryID", "CountryName", c.CountryID);
                ViewBag.State = new SelectList(states, "StateID", "StateName", c.StateID);
                return View(c);
            }
        
Step-2: Add view for the Action & design the form.

Right Click on Action Method (here right click on Add action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.

Here the view design for the edit form will be same as "Add new Contact" view design, just need 2 changes 1. Need to store Contact ID in a hidden field and 2. Have to show image if it exist. So here I copied the HTML code from "Add" View and done the above 2 changes.

HTML Code of Edit View
            
            @model MVCContactBook.Contact
            @{
                ViewBag.Title = "Edit";
            }

            <h2>Edit</h2>
            @* Here we can use the same view which was for Add Contact , just need 2 changes 1. Need to store Contact ID in a hidden field and
            2. Have to show image if it exist  *@
            @using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { @class="form-horizontal", enctype="multipart/form-data"} ))
            {
                @Html.ValidationSummary(true)
                @Html.AntiForgeryToken()     //we need this for prevent CSRF Attack
                @Html.HiddenFor(model=> model.ContactID) // This is our First Changes
                //Here I will customize the form for good looks and support bootstrap responsive view (not mandatory)   
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactPersonFname, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactPersonFname, new { @class="form-control", placeholder="Enter first name"})
                            @Html.ValidationMessageFor(model => model.ContactPersonFname)
                        </div>
                    </div>
        
                 //Same Way We will do all
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactPersonLname, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactPersonLname, new { @class="form-control", placeholder="Enter last name"})
                            @Html.ValidationMessageFor(model => model.ContactPersonLname)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactNo1, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactNo1, new { @class="form-control", placeholder="Enter Contact No1"})
                            @Html.ValidationMessageFor(model => model.ContactNo1)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactNo2, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactNo2, new { @class="form-control", placeholder="Enter Contact No2"})
                            @Html.ValidationMessageFor(model => model.ContactNo2)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.EmailID, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.EmailID, new { @class="form-control", placeholder="Enter Email ID"})
                            @Html.ValidationMessageFor(model => model.EmailID)
                        </div>
                    </div>        
                    <div class="form-group">
                        @Html.LabelFor(model => model.CountryID, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.CountryID, @ViewBag.Country as SelectList,"Select Country", new { @class="form-control"})
                            @Html.ValidationMessageFor(model => model.CountryID)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.StateID, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.StateID, @ViewBag.State as SelectList,"Select State", new { @class="form-control"})
                            @Html.ValidationMessageFor(model => model.StateID)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Address, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextAreaFor(model => model.Address,3,5, new { @class="form-control", placeholder="Enter Address"})
                            @Html.ValidationMessageFor(model => model.Address)
                        </div>
                    </div>        
                    // Here Have to do for File 
                    <div class="form-group">
                        <label class="col-md-2 control-label">Select File : </label>
                        <div class="col-md-5">
                            @Html.TextBox("file", null, new { type="file", @class="form-control", placeholder="Enter Address", accept = "image/x-png, image/gif, image/jpeg"})
                            @Html.ValidationMessage("FileErrorMessage")
                        </div>         
                        @* Here is our 2nd changes for show image if exist *@   
                        <div class="col-md-5" style="display:@(string.IsNullOrEmpty(Model.ImagePath)?"none":"block")">
                            <img src="/image/@Model.ImagePath" alt="image" width="100" />
                        </div>

                    </div>         
        
                   <div class="form-group">
                       <div class="col-md-10 col-md-offset-2">
                            <input type="submit" value="Create" class="btn btn-primary" />
                        </div>
                    </div>

            }

            <div>
                @Html.ActionLink("Back to List", "Index")
            </div>
             @section Scripts {
             @Scripts.Render("~/bundles/jqueryval")
            
        }
        
Step-3: Add new action into your controller for Post form (POST Method) for Edit Contact.

Here I have added "Edit" Action with Model Parameter (here "Contact") into "Home" Controller. Write this following code

            
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Edit(Contact c, HttpPostedFileBase file)
            {
                #region//fetch country & state for dropdown

                List<Country> allCountry = new List<Country>();
                List<State> states = new List<State>();
                using (MyContactBookEntities dc = new MyContactBookEntities())
                {
                    allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
                    if (c.CountryID > 0)
                    {
                        states = dc.States.Where(a => a.CountryID.Equals(c.CountryID)).OrderBy(a => a.StateName).ToList();
                    }
                }
                ViewBag.Country = new SelectList(allCountry, "CountryID", "CountryName", c.CountryID);
                ViewBag.State = new SelectList(states, "StateID", "StateName", c.StateID);

                #endregion
                #region//validate file is selected
                if (file != null)
                {
                    if (file.ContentLength > (512 * 1000)) // 512 KB
                    {
                        ModelState.AddModelError("FileErrorMessage", "File size must be within 512KB");
                    }
                    string[] allowedType = new string[] {"image/png", "image/gif", "image/jpg", "image/jpeg"};
                    bool isFileTypeValid = false;
                    foreach (var i in allowedType)
                    {
                        if (file.ContentType == i.ToString())
                        {
                            isFileTypeValid = true;
                            break;
                        }
                    }
                    if (!isFileTypeValid)
                    {
                        ModelState.AddModelError("FileErrorMessage", "Only .png, .gif and .jpg file allowed");
                    }
                }
                #endregion
                // Update Contact
                if (ModelState.IsValid)
                {
                    //Update Contact
                    if (file != null)
                    {
                        string savePath = Server.MapPath("~/image");
                        string fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
                        file.SaveAs(Path.Combine(savePath, fileName));
                        c.ImagePath = fileName;
                    }

                    using (MyContactBookEntities dc = new MyContactBookEntities())
                    {
                        var v = dc.Contacts.Where(a => a.ContactID.Equals(c.ContactID)).FirstOrDefault();
                        if (v != null)
                        {
                            v.ContactPersonFname = c.ContactPersonFname;
                            v.ContactPersonLname = c.ContactPersonLname;
                            v.ContactNo1 = c.ContactNo1;
                            v.ContactNo2 = c.ContactNo2;
                            v.EmailID = c.EmailID;
                            v.CountryID = c.CountryID;
                            v.StateID = c.StateID;
                            v.Address = c.Address;
                            if (file != null)
                            {
                                v.ImagePath = c.ImagePath;
                            }
                        }
                        dc.SaveChanges();
                    }
                    return RedirectToAction("Index");
                }
                else
                {
                    return View(c);
                }
            }
        
Step-4: Run Application.
MyContactBook : Part 6 - Create Page for Edit existing Contact
Posted By :