选择不要在我的数据库MVC / Json上保存数据

时间:2016-03-17 17:58:35

标签: json asp.net-mvc-5

我不知道为什么它不会在我的数据库中保存AddressBookId表单

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

Mi view

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

Json

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

1 个答案:

答案 0 :(得分:0)

因为您的Dropdown未与Model绑定。您将其创建为独立控件。

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

将列表ID和名称更改为“AddressBookList”。创建隐藏字段以使用模型保留AddressBookId。

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

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

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

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

现在,当提交表单时,Model属性AddressBookId将具有所选值。