ASP.NET MVC
View Model
JSON
Serialization
Web Development

How to convert View Model into JSON object in ASP.NET MVC?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In ASP.NET MVC, converting a view model to JSON is really a serialization step. You either serialize the object so JavaScript can consume it in the browser, or you return it from a controller action as JSON for an AJAX call. The right approach depends on whether the JSON is needed inside a rendered view or as a standalone HTTP response.

Core Sections

Return JSON directly from a controller action

If the client is requesting data asynchronously, the cleanest option is usually to return a JsonResult from the controller.

csharp
1public class OrdersController : Controller
2{
3    public ActionResult DetailsJson(int id)
4    {
5        var model = new OrderViewModel
6        {
7            Id = id,
8            CustomerName = "Ada Lovelace",
9            Total = 149.50m
10        };
11
12        return Json(model, JsonRequestBehavior.AllowGet);
13    }
14}

This tells ASP.NET MVC to serialize the view model and send the JSON in the HTTP response. It is the most appropriate choice when JavaScript will fetch the data with fetch, jQuery AJAX, or another client-side request.

Serialize manually when you need JSON inside the Razor view

Sometimes you already have a view model in a Razor page and want to embed its JSON representation into a script block. In that case, manual serialization is more appropriate.

csharp
1using Newtonsoft.Json;
2
3@model OrderViewModel
4
5<script>
6    const orderModel = @Html.Raw(JsonConvert.SerializeObject(Model));
7    console.log(orderModel.customerName);
8</script>

Html.Raw matters here because otherwise Razor will HTML-encode the JSON string, which breaks the JavaScript.

This pattern is useful for page bootstrapping when server-rendered HTML and client-side behavior share the same initial data.

Keep the view model focused on the client contract

If you serialize a view model directly, the serialized fields become part of the client-visible contract. That is why view models are a better JSON source than domain entities. A view model should expose exactly what the page or API client needs and omit internal properties that do not belong in the browser.

csharp
1public class OrderViewModel
2{
3    public int Id { get; set; }
4    public string CustomerName { get; set; }
5    public decimal Total { get; set; }
6}

This is safer than serializing an entity object that might include navigation properties, internal flags, or data that should never leave the server.

Choose the serializer intentionally

Older ASP.NET MVC applications commonly use JavaScriptSerializer or Json.NET, which is Newtonsoft.Json. Json.NET became popular because it offers better configuration and more predictable serialization behavior for many non-trivial models.

csharp
using Newtonsoft.Json;

var json = JsonConvert.SerializeObject(model, Formatting.Indented);

If you only need a string, manual serialization like this is enough. If you want an HTTP response, returning JsonResult is usually cleaner.

Watch for encoding and script-safety issues

Embedding JSON into HTML can go wrong if you forget the boundary between JSON encoding and HTML encoding. JSON must stay valid JavaScript, and the surrounding page must stay valid HTML.

The safest pattern is:

  • serialize the model once
  • emit it with Html.Raw
  • avoid concatenating untrusted fragments manually

For data returned from a controller action, this is less of a concern because the response body is JSON instead of HTML.

Prefer AJAX or APIs for larger data flows

Inline JSON in a Razor page is fine for small bootstrap payloads. For larger or frequently updated data, it is usually cleaner to expose a dedicated endpoint and load it from the client.

That separation keeps the view focused on rendering and lets the data contract evolve more deliberately.

Common Pitfalls

  • Serializing a domain entity directly instead of a dedicated view model can expose internal or unnecessary data.
  • Forgetting Html.Raw when embedding JSON in Razor causes HTML encoding that breaks the JavaScript object literal.
  • Returning JSON on a GET request without the appropriate MVC settings can trigger framework restrictions in older ASP.NET MVC versions.
  • Mixing manual string concatenation with serialized JSON creates fragile and potentially unsafe output.
  • Sending far more fields than the client actually needs increases payload size and couples the UI too tightly to server internals.

Summary

  • In ASP.NET MVC, converting a view model to JSON is usually either a JsonResult response or manual serialization for the view.
  • Use Json(model, JsonRequestBehavior.AllowGet) when the browser should fetch the data from a controller action.
  • Use a serializer such as Json.NET plus Html.Raw when embedding JSON into a Razor page.
  • Prefer dedicated view models over entities so the JSON matches the client contract cleanly.
  • Treat serialization as part of API design, not just a formatting step.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.