我提交按钮时下拉列表值为空?

时间:2017-09-18 15:51:46

标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-3

当我点击提交按钮时,下拉列表country list国家ID值被传递给控制器​​..当我点击F10键盘按钮时,国家绑定方法被调用。所以再次返回起点所以国家价值再次为Null下面我附上了截图:

<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>

脚本:

<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>

班级值:

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

截屏: 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();
            }

        }

国家/地区代码:

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;
        }

1 个答案:

答案 0 :(得分:2)

您当前正在调用Country_Bind()方法作为您的httppost操作方法中的第一个语句。当您想要在渲染相同视图时重新渲染下拉列表时,实际上需要这样做。

如果你没有做ajax帖子,你应该遵循PRG pattern。成功保存数据后,您应该重定向到呈现视图的GET操作方法。如果Modelstate验证失败,那就是当您返回相同的视图时(以便您可以向用户显示验证消息),并且您需要在此之前重新填充下拉数据。

执行重定向时,ViewData无法传输邮件。请改用TempData

[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");
   }    
 }

在您的情况下,当您执行ajax帖子返回重定向结果时没有意义。如果需要,您可以将url返回到下一页作为json响应的一部分,并在您的ajax调用success / done事件处理程序中使用它并执行适当的操作(重定向到新页面/显示消息给用户)

[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 "});
   }    
 }

确保更新ajax调用的success / done事件处理程序以读取响应(json并执行类似向用户显示消息/隐藏或显示下一个选项卡的内容)

我还注意到你的ajaxifying代码存在问题。由于您要提交ajax表单,因此应通过调用event.preventDefault方法来阻止默认表单提交行为。

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

我还建议使用特定于视图的平坦视图模型。所以你的属性不会是嵌套级别,当你使用辅助方法(TextBoxFor etx)时,它会生成正确的输入字段名称,你不需要手动构建你要发送的Js对象 。您可以在表单对象上使用jquery serialize()方法,并将其作为ajax调用的数据发送。

相关问题