2017-09-24 65 views
-1

假設我要顯示客戶的地址和聯繫人號碼。有一個下拉選擇客戶,我必須顯示所選客戶的地址和聯繫電話號碼。將對象作爲控制器的Json結果傳遞給視圖

我創建了一個存儲過程來返回客戶地址和聯繫電話號碼。

這是客戶在視圖中的下拉菜單。

<div class="form-group"> 
        @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-4" }) 
        <div class="col-md-8"> 
         @Html.DropDownListFor(model => model.CustomerName, new SelectList(ViewBag.CustomerName, "Id", "Name"), "Select Customer", new { @class = "form-control", id = "cmbCustomerList" }) 
         @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" }) 
        </div> 
       </div> 

這是我到目前爲止試過的腳本。

「#AddressSection」:地址和聯繫號碼顯示區域

「#cmbCustomerList」:客戶下拉列表

「銷售/ GetCustomerDetails」:控制器和動作

$(document).ready(function() { 

//Address Section 
$("#AddressSection").hide(); 
$('#cmbCustomerList').change(function() { 
    if ($('#cmbCustomerList :selected').text() == "Select Customer") { 
     $("#AddressSection").hide(); 
    } 
    else { 
     $("#AddressSection").show();   
     var selectedVal = $(this).find(':selected').val(); 
     $.get("/Sales/GetCustomerDetails/" + selectedVal, function (data, status) { 
      //Here I want to pass the values to the address and contact number labels 
     }); 
    } 
}); 
}); 

這是控制器中的動作

public JsonResult GetCustomerDetails(int id) 
     { 
      List<CustomerViewModel> customer = _handler.GetCustomerDetails(id); 
      return Json(customer, JsonRequestBehavior.AllowGet); 
     } 

有一個在視圖中重新輸入3個標籤以顯示地址和聯繫人號碼。

<label id="lblAddressLine1" /> 
<label id="lblAddressLine2" /> 
<label id="lblContactNumber" /> 

在CustomerViewModel有3個屬性 AddressLine1, AddressLine2, ContactNumber

所以我的問題是如何單獨視圖訪問這些3點的屬性?

謝謝。

+0

顯示您要與客戶的詳細信息,以更新元素的HTML。當你只想要一個客戶的細節時,爲什麼你要返回'List ? –

+0

+0

在問題中,不在評論中。而你仍然沒有解釋爲什麼你返回一個集合 –

回答

0

我沒有得到爲什麼你返回集合如果有客戶詳細信息只反正你可以使用$。每個循環

$.get("/Sales/GetCustomerDetails/" + selectedVal, function (data, status) { 
      $.each(data, function (index, item) { 
        $("#txtAddressLine1").text(item.AddressLine1); 
      }); 
}); 
相關問題