![](/img/trans.png)
[英]How to assign c# guid value to javascript variable using razor viewmodel in asp.net mvc?
[英]MVC6 Assign a viewmodel list property to a javascript variable
我有一個具有以下屬性的視圖模型:
public class CompanyDetailsViewModel
{
[Required(ErrorMessage = "A Company Name is required")]
[Display(Name = "Company Name:")]
[StringLength(100)]
public string CompanyName { get; set; }
...
public IList<SuburbAndPostcode> SuburbAndPostcodesList { get; set; }
}
該列表是從此POCO類創建的:
public class SuburbAndPostcode
{
[Key]
public int SuburbsAndPostcodesId { get; set; }
public string Suburb { get; set; }
public string PostCode { get; set; }
public State State { get; set; }
}
這是狀態對象:
public class State
{
[Key]
public int StateId { get; set; }
public string ShortName { get; set; }
public string Name { get; set; }
public virtual ICollection<CompanyDetail> CompanyDetails { get; set; }
}
我試圖創建一個具有郊區和郵政編碼屬性的變量作為列表,可以將其用於自動完成功能,但是我似乎無法將Model.SuburbsAndPostCodesList分配給變量。
我試圖從這個論壇上跟其他的問題表示的各種JavaScript選項這里 。
我想有一個代表列表的javascript變量,我已經嘗試過設置:
var suburbs = @Model.SuburbAndPostcodesList
我已經嘗試過使用json並嘗試遍歷模型,但是收到一條錯誤消息,指出變量“ test”不在上下文中:
var test =[];
@for (int i = 0; i < Model.SuburbAndPostcodesList.Count; i++)
{
test[i]=...
}
我也嘗試過使用“ push”和“ .Encode”。
我想知道如何將此字符串和狀態對象列表分配給javascript變量?
使用Ajax Call實現自動完成功能
$(document).ready(function () {
$("#txtPostcodes").keyup(function () {
//AutoComplete the Results
$("#txtPostcodes").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../ControllerName/ActionName",
data: "{'input':'" + document.getElementById('txtPostcodes').value + "'}",
dataType: "json",
success: function (data) {
if (data != null) {
var suburbs = data;
}
},
error: function (result) {
}
});
}
});
}
});
});
最后,我簡單地將viewmodel列表的各個成員等同起來,並為自動完成功能建立了一個javascript多維數組。 這里是:
var suburbs = [
@for (var i = 0; i < Model.SuburbAndPostcodesList.Count; i++) {
<text>{
id: "@Model.SuburbAndPostcodesList[i].SuburbsAndPostcodesId",
suburb: "@Model.SuburbAndPostcodesList[i].Suburb",
postCode: "@Model.SuburbAndPostcodesList[i].PostCode",
state: "@Model.SuburbAndPostcodesList[i].State.ShortName"
}@(i == Model.SuburbAndPostcodesList.Count - 1 ? "" : ",")</text>
}
];
$("#Suburb").autocomplete({
source: function (req, responseFn) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
var a = $.grep(suburbs, function (item, index) {
return matcher.test(item.suburb);
});
a = $.map(a, function (x) {
return {
label: x.suburb + " - " + x.postCode,
value: x.suburb,
suburbDetails: x
};
});
responseFn(a);
},
select: function (value, data) {
if (typeof data == "undefined") {
} else {
$("#Postcode").val(data.item.suburbDetails.postCode);
}
},
change: function (event, ui) {
if (!ui.item) {
$("#Suburb").val("");
$("#Postcode").val("");
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.