选择“不在我的数据库 MVC/JSON 上保存数据”



我不知道为什么它不在我的数据库中保存地址书ID表单

public class CreditCard
  {
  public int Id { get; set; }
  [Display (Name="Customer")]
  public int CustomerID { get; set; }
  [Display(Name = "Billing Address")]
  public int AddressBooKId { get; set; }
  public virtual Customer Customer { get; set; }
  }

控制器:

 public ActionResult Create()
 {
  ViewBag.CustomerID = new SelectList(db.Customers, "Id", "FullName");
  ViewBag.CCTypeId = new SelectList(db.CreditCardTypes, "Id", "CCName");
  return View();
 }
   public JsonResult AddList(int Id)
   {
   var add = from a in db.AddressBooks
   where a.CustomerId== Id
   select a;
   return Json(new SelectList(add.ToArray(), "AddressBookId", "Address"), JsonRequestBehavior.AllowGet);
   }
   public IList<AddressBook> Getadd(int CustomeId)
   {
   return db.AddressBooks.Where(m => m.CustomerId== CustomeId).ToList();}

小米视图

   <div class="form-group">
   @Html.LabelFor(model => model.AddressBooKId, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
  <select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select><br />
   @Html.ValidationMessageFor(model => model.AddressBooKId, "", new { @class = "text-danger" })
  </div>
  </div>
  <div class="form-group">

杰森

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/jscript">
 $(function () {
 $('#AddressBooKId').html(null)
         $('#CustomerID').change(function () {
             $.getJSON('/CreditCards/AddList/' + $('#CustomerID').val(), function (data) {
             var items = '<option>Select a Address</option>';
              $.each(data, function (i, add) {
               items += "<option value='" + add.Value + "'>" + add.Text + "</option>";                       });
                $('#AddressBooKId').html(items);
                   });       });            });
          </script>

因为您的下拉列表未绑定模型。您正在将其创建为独立控件。

<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select>

将列表 ID 和名称更改为"地址簿列表"。创建隐藏字段以使用模型保留地址簿 ID。

@Html.HiddenFor(m => m.AddressBooKId);

更改 JS 代码以更新新的下拉列表名称。

为 AddressBookList 创建新的更改事件处理程序,并设置 HiddenField 的值。

$('#AddressBookList').change(function () {
  $('#AddressBooKId').val($('#AddressBookList').val());
}

现在,当提交表单时,模型属性 AddressBookId 将具有选定的值。

最新更新