You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Razor模型数据更新Knockout ViewModel?.NET Core MVC场景

Hey there, let's walk through the common issues that might be causing your Knockout ViewModel to come up empty when trying to pull data from your .NET Core MVC Razor model. I've been in your shoes before, so let's break this down step by step.

Common Causes & Fixes

1. Razor Model Data Isn't Properly Passed to the Client

The most frequent issue is failing to correctly serialize your .NET model into a format Knockout can use (JSON). If you just try to reference @Model.Property directly in JS, you might hit encoding issues or end up with malformed data.

Fix: Use .NET's JSON serializer to convert your model into a valid JSON object, then inject it into your script with @Html.Raw() to avoid HTML encoding:

<script>
    // Serialize the Razor model to JSON (use System.Text.Json by default in .NET Core)
    var serverData = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model));
    
    // Initialize Knockout ViewModel (using the mapping plugin for simplicity)
    var viewModel = ko.mapping.fromJS(serverData);
    ko.applyBindings(viewModel);
</script>
  • If you prefer Newtonsoft.Json (Json.NET), install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package and use:
    var serverData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
    
  • Watch out for circular references in your model—add ReferenceHandler.IgnoreCycles to your serializer options if needed to avoid serialization failures.

2. Knockout Binding Syntax Mismatches

Knockout is case-sensitive, so if your Razor model has a property like Name (PascalCase), your binding must match exactly. A typo here will leave fields empty.

Example of a Mistake:

<!-- Wrong: uses lowercase 'name' but model property is 'Name' -->
<input data-bind="value: name" />

Correct Version:

<input data-bind="value: Name" />

Pro Tip: Open your browser's dev tools (F12) and check the console—Knockout will throw errors like "Unable to parse bindings" if it can't find the property, which points you straight to the issue.

3. Knockout Initializes Before the DOM is Ready

If you run ko.applyBindings() before the HTML elements you're binding to exist, Knockout can't attach the data, leaving fields empty.

Fix: Wrap your initialization code in a DOM-ready event listener:

<script src="~/lib/knockout/knockout-latest.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        var serverData = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model));
        var viewModel = ko.mapping.fromJS(serverData);
        ko.applyBindings(viewModel);
    });
</script>

Alternatively, place your script at the very bottom of the page, right before the closing </body> tag.

4. Your Razor Model is Empty to Begin With

Before blaming Knockout, confirm your backend is actually passing data to the view.

Quick Check:
Add a raw output of your model property in the Razor view:

<!-- Test if the model has data -->
<p>Raw Model Name: @Model.Name</p>

If this shows nothing, your GET Action isn't populating the model correctly. Add a breakpoint in your Action method to verify you're setting properties like return View(new MyModel { Name = "Jane Doe" });.

5. Missing Knockout Mapping Plugin (If You're Using It)

If you're using ko.mapping.fromJS() to auto-generate your ViewModel, you need to include the knockout mapping script in your page. Without it, the method won't exist, and your ViewModel won't initialize.

Fix: Add the mapping script after the core Knockout script:

<script src="~/lib/knockout/knockout-latest.js"></script>
<script src="~/lib/knockout-mapping/knockout.mapping-latest.js"></script>

If you don't want to use the mapping plugin, you can define your ViewModel manually:

var viewModel = {
    Id: ko.observable(serverData.Id),
    Name: ko.observable(serverData.Name),
    Email: ko.observable(serverData.Email)
};
A Full Working Example

Let's put this all together to give you a reference:

Backend Action

public IActionResult UserProfile()
{
    var user = new UserViewModel
    {
        Id = 123,
        FullName = "Winthorpe",
        Email = "winthorpe@example.com"
    };
    return View(user);
}

public class UserViewModel
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
}

Razor View

@model UserViewModel

<h2>User Profile</h2>

<div class="form-group">
    <label>Full Name:</label>
    <input type="text" class="form-control" data-bind="value: FullName" />
</div>
<div class="form-group">
    <label>Email:</label>
    <input type="email" class="form-control" data-bind="value: Email" />
</div>

<script src="~/lib/knockout/knockout-latest.js"></script>
<script src="~/lib/knockout-mapping/knockout.mapping-latest.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        var serverData = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model));
        var viewModel = ko.mapping.fromJS(serverData);
        ko.applyBindings(viewModel);
    });
</script>
Note on .NET Core + Knockout Docs

It's true official .NET Core-specific Knockout docs are sparse, but remember: Knockout is a frontend library—its core behavior doesn't change with the backend framework. The only .NET-specific part is serializing your model to JSON, which we covered above. Most general Knockout tutorials will work perfectly with .NET Core once you nail that data handoff.

内容的提问来源于stack exchange,提问作者Winthorpe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:25:26