-1

Form having dropdown country list when i click on submit button country ID value is passed to the controller..when i click on F10 keybord button country bind method is called .so again return to starting point so that again country value is Null Below i attached the screen shot:

<div class="page-content">
    <div class="container-fluid">
        <header class="section-header">
            <div class="tbl">
                <div class="tbl-row">
                    <div class="tbl-cell">
                        <h2>Company Registration Form</h2>
                    </div>
                </div>
            </div>
        </header>
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)
            <section class="tabs-section">
                <div class="tabs-section-nav tabs-section-nav-icons">
                    <div class="tbl">
                        <ul class="nav" role="tablist">
                            <li class="nav-item">
                                <a class="nav-link active" href="#tabs-1-tab-1" role="tab" data-toggle="tab">
                                    <span class="nav-link-in">
                                        <i class="font-icon font-icon-cogwheel"></i>
                                        Company Registration Form
                                    </span>
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#tabs-1-tab-2" role="tab" data-toggle="tab">
                                    <span class="nav-link-in">
                                        <span class="glyphicon glyphicon-music"></span>
                                        Company Social Network
                                    </span>
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#tabs-1-tab-3" role="tab" data-toggle="tab">
                                    <span class="nav-link-in">
                                        <i class="fa fa-product-hunt"></i>
                                        Company Reference
                                    </span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </div><!--.tabs-section-nav-->
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane fade in active show" id="tabs-1-tab-1">
                        <br />
                        <br />
                        <section>
                            <div>
                                <div class="row">
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => Model.company.CompanyName, new { @class = "form-label semibold control-label" })
                                            @Html.TextBoxFor(model => model.company.CompanyName, new { @class = "form-control", @id = "txtCompanyName", placeholder = "Enter the Company Name" })
                                            @Html.ValidationMessageFor(model => model.company.CompanyName)
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.ShortName, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.ShortName, new { @class = "form-control", @id = "txtShortName", placeholder = "Enter the Short Name" })
                                            @Html.ValidationMessageFor(model => model.company.ShortName)
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.Division, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.Division, new { @class = "form-control", @id = "txtDivision", placeholder = "Enter the Division" })
                                            @Html.ValidationMessageFor(model => model.company.Division)
                                        </fieldset>
                                    </div>
                                </div><!--.row-->
                                <br />
                                <div class="row">
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.Email, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.Email, new { @class = "form-control", @id = "txtEmail", placeholder = "Enter your Email" })
                                            @Html.ValidationMessageFor(model => model.company.Email)
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.Address1, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.Address1, new { @class = "form-control", @id = "txtAddress1", placeholder = "Enter your Address Line 1" })
                                            @Html.ValidationMessageFor(model => model.company.Address1)
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.Address2, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.Address2, new { @class = "form-control", @id = "txtAddress2", placeholder = "Enter your Address Line 2" })
                                        </fieldset>
                                    </div>
                                </div><!--.row-->
                                <br />
                                <div class="row">
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.Country, new { @class = "form-label semibold" })
                                            @Html.DropDownList("Country", null, "--- Select Country ---", new { @class = "select2-arrow" })
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.State, new { @class = "form-label semibold" })
                                            <select id="state" class="select2-arrow"></select>
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.City, new { @class = "form-label semibold" })
                                            <select id="city" class="select2-arrow"></select><br />

                                        </fieldset>
                                    </div>
                                </div><!--.row-->
                                <br />
                                <div class="row">
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.Pincode, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.Pincode, new { @class = "form-control", @id = "txtPincode", placeholder = "Enter your Pincode" })
                                            @Html.ValidationMessageFor(model => model.company.Pincode)
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.CountryCode, new { @class = "form-label semibold" })
                                            @*@Html.DropDownList("CountryCode", null, "---Select CountryCode---", new { @class = "select2-arrow" })*@
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.MobileNo, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.MobileNo, new { @class = "form-control", @id = "txtMobileNo", placeholder = "Enter your Mobile Number" })
                                            @Html.ValidationMessageFor(model => model.company.MobileNo)
                                        </fieldset>
                                    </div>
                                </div><!--.row-->
                                <br />
                                <div class="row">
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.PhoneNo, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.PhoneNo, new { @class = "form-control", @id = "txtPhoneNo", placeholder = "Enter your PhoneNo" })
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.PanNo, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.PanNo, new { @class = "form-control", @id = "txtPanNo", placeholder = "Enter Company PanNo" })
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.TinNo, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.TinNo, new { @class = "form-control", @id = "txtTinNo", placeholder = "Enter Company TinNo" })
                                        </fieldset>
                                    </div>
                                </div><!--.row-->
                                <br />
                                <div class="row">
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.GSTno, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.GSTno, new { @class = "form-control", @id = "txtGSTno", placeholder = "Enter Company GSTno" })
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.company.IECCode, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.company.IECCode, new { @class = "form-control", @id = "txtIECCode", placeholder = "Enter Company IECCode" })
                                        </fieldset>
                                    </div>

                                </div><!--.row-->
                                <br />
                                <div class="row">
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            <label class="form-label semibold">Upload Company Logo</label>&nbsp;&nbsp;
                                            <input type="file" name="file" id="txtUploadImage" style="cursor:pointer;" />
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            <label class="form-label semibold">Perview Image</label>&nbsp;&nbsp;
                                            <img id="image_upload_preview" src="http://placehold.it/100x100" alt="your image" />
                                            <a id="remove" onclick="javascript:ClearFileUploadControl();" style="display: none; cursor: pointer;">Remove</a>
                                        </fieldset>
                                    </div>
                                </div>
                                <br />
                                <input type="submit" name="Submit" id="SaveCompany" value="Save" class="btn btn-rounded btn-inline btn-success" />
                            </div>
                        </section>

                    </div><!--.tab-pane-->
                    <div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-2">
                        <br />
                        <section>
                            <div>
                                <div class="row">
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.CompanySocial.FaceBookID, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.CompanySocial.FaceBookID, new { @class = "form-control", @id = "txtFaceBookID", placeholder = "Enter the Facebook Link" })
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.CompanySocial.TwitterID, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.CompanySocial.TwitterID, new { @class = "form-control", @id = "txtTwitterID", placeholder = "Enter the Twitter Link" })
                                        </fieldset>
                                    </div>
                                    <div class="col-lg-4">
                                        <fieldset class="form-group">
                                            @Html.LabelFor(model => model.CompanySocial.linkedinID, new { @class = "form-label semibold" })
                                            @Html.TextBoxFor(model => model.CompanySocial.linkedinID, new { @class = "form-control", @id = "txtlinkedinID", placeholder = "Enter the Linkedin Link" })
                                        </fieldset>
                                    </div>
                                </div><!--.row-->
                            </div>
                        </section>
                        <input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step " />
                        <input type="submit" name="Submit" id="saveSocial" value="Next" class="btn btn-rounded btn-inline btn-success" />
                    </div><!--.tab-pane-->
                    <div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-3">
                        Tab 3
                        <br />
                        <br />
                        <input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step" />
                        <input type="submit" name="Submit" value="Finish" class="btn btn-rounded btn-inline btn-success" />
                    </div><!--.tab-pane-->
                </div><!--.tab-content-->
            </section><!--.tabs-section-->
        }
    </div>
</div>

Scripts:

<script>
        function GetInfo() {
            var Company = {
                CompanyName: $("#txtCompanyName").val(), ShortName: $("#txtShortName").val(), Division: $("#txtDivision").val(), Email: $("#txtEmail").val(), Address1: $("#txtAddress1").val(), Address2: $("#txtAddress2").val(), Country: $("#Country").val(), State: $("#state").val(), City: $("#city").val(),
                Pincode: $("#txtPincode").val(), MobileNo: $("#txtMobileNo").val(), PhoneNo: $("#txtPhoneNo").val(), PanNo: $("#txtPanNo").val(), TinNo: $("#txtTinNo").val(), GSTno: $("#txtGSTno").val(), IECCode: $("#txtIECCode").val()
            };

            var mainModel = {};
            mainModel.Company = Company;

            $.ajax({
                type: "POST",
                url: "/Company/AddCompany",
                data: JSON.stringify(mainModel),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
        }

        function OnSuccess(response) {
            alert(response.d);
        }

        $(document).ready(function () {
            $("#saveSocial").click(function (e) {
                e.preventDefault();
                GetInfo1();
            });

            $("#SaveCompany").click(function (e) {
                //e.preventDefault();
                GetInfo();
            });
        });


        function GetInfo1() {
            var Social = { FaceBookID: $("#txtFaceBookID").val(), TwitterID: $("#txtTwitterID").val(), linkedinID: $("#txtlinkedinID").val() };

            var mainModel = {};
            mainModel.CompanySocial = Social;

            $.ajax({
                type: "POST",
                url: "/Company/AddSocial",
                data: JSON.stringify(mainModel),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
        }
    </script>

    <script>
        $(document).ready(function () {
            $("#Country").change(function () {
                var id = $(this).val();
                $("#state").empty();
                $.get("State_Bind", { CountryID: id }, function (data) {
                    var v = "<option>--- Select State ---</option>";
                    $.each(data, function (i, v1) {
                        v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
                    });
                    $("#state").html(v);
                });
            });

            $("#state").change(function () {
                var id = $(this).val();
                $("#city").empty();
                $.get("City_Bind", { StateID: id }, function (data) {
                    var v = "<option>--- Select City---</option>";
                    $.each(data, function (i, v1) {
                        v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
                    });
                    $("#city").html(v);
                });
            });
        });
    </script>

Class value:

public int Country { get; set; }
        public int State { get; set; }
        public int City { get; set; }

Screen shot: First photo

Empty Country

ActionResult:

[HttpPost]
        public ActionResult AddCompany(MainModel mainModel)
        {

            try
            {

                Country_Bind();

                if (ModelState.IsValid)
                {
                    dp obj = new dp();
                    if (obj.AddNewCompany(mainModel))
                    {
                        ViewBag.Message = "Company added successfully";
                    }
                }

                return View();
            }

            catch
            {
                return View();
            }

        }

Country code:

public void Country_Bind()
        {
            DataSet ds = dblayer.Get_Country();
            List<SelectListItem> coutrylist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                coutrylist.Add(new SelectListItem { Text = dr["CountryName"].ToString(), Value = dr["CountryID"].ToString() });
            }
            ViewBag.Country = coutrylist;
        }
Ivin Raj
  • 3,448
  • 2
  • 28
  • 65

1 Answers1

2

You are currently calling the Country_Bind() method as the first statement inside your httppost action method. You actually need to do that when you want to rerender the dropdown list when re rendering the same view.

If you are not doing an ajax post,You should follow the PRG pattern. On successful save of the data, you should redirect to the GET action method which render the view. If the Modelstate validation fails, that is when you return the same view (so that you can show the validation message to user) and you need to repopulate the dropdown data before that.

When you do a Redirect, ViewData does not work to transfer messages.Use TempData instead.

[HttpPost]
public ActionResult AddCompany(MainModel mainModel)
{    
    try
    {
       if (ModelState.IsValid)
       {
            dp obj = new dp();
            if (obj.AddNewCompany(mainModel))
            {
                TempData.Message = "Company added successfully";
                return RedirectToAction("CompanyList");
            }
       }
       // We need to repopulate the data needed for rendering dropdown
       Country_Bind();
       return View(mainModel);
   }
   catch(Exception ex)
   {
      // to do : Make sure to log the error
      return View("Error");
   }    
 }

In your case, when you do an ajax post returning a redirect result does not makes sense. You may return the url to the next page if needed as part of a json response and use that in your ajax calls success/done event handler and do appropriate things (redirect to the new page/show a message to user)

[HttpPost]
public ActionResult AddCompany(MainModel mainModel)
{    
    try
    {
       if (ModelState.IsValid)
       {
            dp obj = new dp();
            if (obj.AddNewCompany(mainModel))
            {
                return Json(new { Message="Company added successfully"});
            }
       }          
       return Json(new { Message="Validation errors!"});
   }
   catch(Exception ex)
   {
       // must log the exception
       return Json(new { Message="Error "});
   }    
 }

Make sure to update your success/done event handler of your ajax call to read the response (the json and do something like showing message to user/hiding or showing the next tab)

I also noticed an issue with your ajaxifying code. Since you are making an ajax form submission, you should prevent the default form submit behavior by calling the event.preventDefault method.

$("#SaveCompany").click(function (e) {
    e.preventDefault();
    GetInfo();
});

I would also recommend to use a flat-lean view model specific for the view. So your properties will not be nested level and when you use the helper methods (TextBoxFor etx), It will generate the correct input field names and you do not need to manually build the Js object you want to send. You may simply use the jquery serialize() method on your form object and send that as the data for the ajax call.

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • If am using the e.preventDefault()..form validation is not working .. alert message is not showing if am not using in this method the validation is working .show alert messages.. – Ivin Raj Sep 18 '17 at 17:05
  • check it my recently comment @shyju – Ivin Raj Sep 18 '17 at 17:11
  • your comment does not make sense (to a person who does not physically see your project source code). you say form validation is not working ? What is happening now ? since you are doing an ajax form submit, the validation helper methods are of no use in the view. You could read the validation errors and send that in your json response and show that to the user. Refer [this post](https://stackoverflow.com/questions/39379711/asp-net-4-how-pass-the-errors-objects-to-a-json/39379935#39379935) – Shyju Sep 18 '17 at 17:14
  • I have one doubt e.preventDefault() if I use on button click . Page is loading stoped and validation message is not showing .. @Shyju – Ivin Raj Sep 18 '17 at 17:22
  • `preventDefault` stops the normal submit button click behavior. When you do ajax form submit, you are only sending some data to server asynchronously. in that case, you want to prevent the default form submit behavior, which submits the entire form to the sever and server may return a new view with validation errors. If you are using the mvc validation helpers, the server side validation error messages won't appear in your view when you do an ajax form post. You can still do client side validation for the form( Refer [this post](https://stackoverflow.com/questions/14005773#14061592)) – Shyju Sep 18 '17 at 17:28