如何让 Knockout.Mapping 在 ASP.NET Web App 中工作?

How can I make Knockout.Mapping working in ASP.NET Web App?

我正在构建一个 MVC5 Web 应用程序并希望使用 Knockout.js 进行动态页面视图。但是,我发现 Knockout.Mapping 在我的项目中似乎无法正常工作。

如您所见,Intellisense 没有针对映射插件的建议(我在 _reference.js 中包含了插件的参考)。当我强行完成这一行时,它没有显示第二个警告。

我是否需要做更多的事情才能使其正常工作?

@if (false)
{
<script src = "~/Scripts/knockout-3.4.0.js" ></script >
<script src = "~/Scripts/knockout.mapping-latest.js"></script >
}

<script type="text/javascript" src="@Url.Content("~/Scripts/knockout-3.4.0.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/knockout.mapping-latest.js")"></script>

//~~body~~//

<script type="text/javascript">
alert("1");
var json = '@Html.Raw(Json.Encode(Model))';
b = ko.mapping.fromJson(json); //"mapping" is not suggested when "ko." is put.
//b = ko.mapping.fromJson(Model); //mistake at the original post
ko.applyBindings(b);
alert("2"); // not showed when the previous two lines is active.
</script>

查看可用的帮助 here

我认为您需要创建映射的示例是这样的:

ko.mapping.fromJS(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)))

试试这个。

 var ViewModel = function() {
   var self = this;

   self.formData2 = ko.mapping.fromJS(@Html.Raw(Json.Encode(Model)));
 }

并在您的控制器中:

public ActionResult Index()
    {

        return View(new ExecutivoViewModel());
    }

我的 ViewModel Class:

 public class ExecutivoViewModel
{
    public ExecutivoViewModel() { }

    public ExecutivoViewModel(Executivo entidade)
    {
        this.ExecutivoId = entidade.ExecutivoId;
        this.Nome = entidade.Nome;
        this.Cargo = entidade.Cargo;
        this.Inativo = entidade.Inativo;
    }

    [DisplayName("Executivo ID")]
    [Required]
    public int ExecutivoId { get; set; }

    [DisplayName("Nome")]
    [MaxLength(50)]
    [Required]
    public string Nome { get; set; }

    [DisplayName("Cargo")]
    [MaxLength(50)]
    [Required]
    public string Cargo { get; set; }

    [DisplayName("Inativo")]
    public bool Inativo { get; set; }

抱歉耽误了跟进。最后我通过使用

使它工作
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>    

//~~body~~//

@section scripts{
        <script src="~/Scripts/knockout-3.4.0.js"></script>
        <script src="~/Scripts/knockout.mapping-latest.js"></script>
}

并通过放置

显示建议
/// <reference path="knockout.mapping-latest.js" />

在_reference.js中引用了knockout.js的核心库后。