2016-03-17 114 views
0

我不知道爲什麼它不保存AddressBookId形成選擇在我的數據庫選擇不保存在我的數據庫MVC/JSON數據

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

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

回答

0

因爲您的下拉列表不與模型綁定。您正在將其創建爲獨立控制。

<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將具有選定的值。