CSharp - 在提交按钮时 C# 下拉 List 值为空?

  显示原文与译文双语对照的内容
75 2

在我点击提交按钮国家/地区国家ID值的表单时,当单击keybord按钮国家绑定方法时,我再次返回的是. so,下面的国家值是 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;
 }
时间:原作者:0个回答

114 4

你目前正在调用 Country_Bind() 方法作为httppost操作方法中的第一条语句。实际上需要在呈现相同视图时使用下拉菜单来完成。

如果你不做ajax文章,你应该按照PRG Pattern 。成功保存数据时,应重定向到呈现视图的获取操作方法。如果Modelstate验证失败,那就是在返回同一视图( 这样你就可以向用户显示验证消息) 时,需要重新填充下面的数据。

在进行重定向时,数据透视表不能用于传输 messages.Use 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 post时,收费并不明智。如果需要作为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"});
 } 
 }

要想读取响应( json和do之类的信息),请确保更新你的ajax调用成功/完成事件处理程序,以读取响应( 如向用户显示消息或者显示

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

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

我还建议使用一个针对视图的平面精益视图模型。所以你的属性不会被嵌套,当你使用 helper 方法时,它会生成正确的输入字段名称,你不需要手工构建你想要发送的Js对象。你可以简单地在表单对象上使用 jquery serialize() 方法,并将它的作为ajax调用的数据发送。

原作者:
...