您可以为JavasScript模型创建一个构造函数,然后使用剃刀代码实例化该构造函数。
例如:
模型
public class Car{
public string Brand { get; set; }
public string Fuel { get; set; }
}
模块模式中的Javascript文件,但您也可以使用其他内容:
var car = (function(jsonModel){
var runs = "My " + jsonModel.Brand + " runs on " + jsonModel.Fuel;
return {
Runs : runs
}
});
剃刀视图
@model Car
$(function(){
var myFord = new car(@Html.Raw(Json.Encode(@Model)) );
alert(myFord.Runs);
});
.NET小提琴我无法添加外部javascript文件,但您可能会明白这一点
尽管我应该说不建议使用@ Html.Raw,因为它会使您容易受到XSS攻击(搜索后在Internet上了解更多信息)。 最好从您的控制器返回JSON对象。
编辑
这是一个如何在.Net小提琴控制器上使用JsonResult的示例
[HttpGet]
public JsonResult Car()
{
return Json(new Car("ford","gasoline"), JsonRequestBehavior.AllowGet);
}
剃刀查看JS以获取json结果并实例化您的JS模块
$(function(){
var model = $.ajax({
url: "@Url.Action("Car","Home")",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
}).done(function(response){
console.log(response);
var myFord = new car(response);
alert(myFord.Runs);
});
});