Skip to content
General ITAdvanced

Best Practices for Passing Objects from View to Controller in ASP.NET Core MVC

Quick Answer The best practice for passing an object from a view to a controller in ASP.NET Core MVC is to pass a unique identifier, retrieve the correspondi...

BI
Bison Technical Team Enterprise IT specialists
Updated 41 min read 0 total views
Structured technical guidanceSafety notes included where requiredSources cited when applicable

Quick Answer

The best practice for passing an object from a view to a controller in ASP.NET Core MVC is to pass a unique identifier, retrieve the corresponding object from a server-side data source, and map it to a strongly typed view model. When the user submits changes, ASP.NET Core MVC uses model binding to populate the controller action parameters from the submitted request data.

ASP.NET Core MVC does not automatically transfer the entire object declared using the Razor @model directive back to a controller. Only values included in the HTTP request, such as named form fields, route parameters, query-string parameters or supported request-body data, are available for model binding.

Advertisement

If an object has not yet been saved to a database, it can be temporarily maintained using session state, a distributed cache or a dedicated server-side draft store. For small, non-sensitive objects, hidden form fields may also be appropriate, provided that all submitted values are validated on the server.

Recommended approach: Use a unique object or draft identifier, dedicated view models, server-side state management, model validation and resource-level authorization instead of attempting to transfer an entire application or database entity between views.

Understanding Data Transfer in ASP.NET Core MVC

ASP.NET Core MVC follows the Model-View-Controller architectural pattern, which separates application data, presentation and request-processing responsibilities.

  • Model: Represents application data, business information and related validation rules.
  • View: Generates the user interface, typically using Razor syntax and HTML.
  • Controller: Processes incoming HTTP requests, performs application operations and returns an appropriate response.
  • ViewModel: Represents the specific information required by a view or accepted from a user interaction.

When a controller returns a view with a model, the Razor view engine uses that object to generate HTML. The browser receives the generated response, not the original C# object instance.

For example, a controller might return a product object to a view:

public IActionResult Details()
{
    var product = new Product
    {
        Id = 101,
        Name = "Wireless Keyboard",
        Description = "USB wireless keyboard"
    };

    return View(product);
}

The corresponding Razor view can display the object:

@model Product

<h2>@Model.Name</h2>
<p>@Model.Description</p>

After the response is generated, the browser has the rendered HTML. It does not hold a reference to the original server-side Product instance.

When the user clicks a link or submits a form, the browser creates another HTTP request. The application must explicitly retrieve, reconstruct or bind the information required to process that request.

Why a Razor Model Is Not Automatically Passed Back to the Controller

Consider the following Razor view:

@model MyModel

<form asp-controller="Home"
      asp-action="Update_DB"
      method="post">

    <a class="btn btn-primary"
       asp-action="Manual">
        Manual
    </a>

    <button type="submit"
            class="btn btn-warning">
        Update Database
    </button>

</form>

Although the view declares @model MyModel, it does not contain any named form controls representing the properties of that model.

Consequently, submitting the form does not send the model's property values to the controller. Other request information, such as an automatically generated antiforgery token, may still be submitted.

For example:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Update_DB(MyModel model)
{
    return View(model);
}

For a conventional MVC complex-type model, the action may receive an object whose properties contain null values, default values or property initializer values because the necessary request data was not supplied. Validation errors may also occur, depending on the model definition.

Important distinction between a link and a submit button

The anchor element and the submit button in the example perform different operations.

Element Typical HTTP Method Behaviour
<a asp-action="Manual"> GET Navigates to the Manual action without submitting the surrounding form.
<button type="submit"> Determined by the form method Submits the form to its configured destination.
<input asp-for="Name"> Determined by the form method Creates a named form control whose value can participate in form submission.
@model MyModel Not applicable Specifies the strongly typed model used by the Razor view.

Placing an anchor element inside a form does not cause that anchor to submit the form. To pass information through a link, supply route or query-string parameters. To submit form values, use a submit button.

How Model Binding Works in ASP.NET Core MVC

Model binding is the process through which ASP.NET Core converts incoming request data into action parameters and .NET objects.

Depending on the action configuration and binding source, model binding can obtain values from:

  • HTML form fields.
  • Route parameters.
  • Query-string parameters.
  • Uploaded files.
  • Request bodies processed through configured input formatters, such as JSON requests handled using [FromBody].
  • Custom model binders and value providers.

For example, consider the following view model:

public class ProductEditViewModel
{
    public int Id { get; set; }

    public string Name { get; set; } = string.Empty;

    public string Description { get; set; } = string.Empty;
}

The Razor view contains form controls associated with these properties:

@model ProductEditViewModel

<form asp-action="Edit" method="post">

    <input asp-for="Id" type="hidden" />

    <label asp-for="Name"></label>
    <input asp-for="Name" />

    <label asp-for="Description"></label>
    <textarea asp-for="Description"></textarea>

    <button type="submit">Save</button>

</form>

The Input and Textarea Tag Helpers generate the appropriate HTML field names. When the form is submitted, those names allow the model binder to associate incoming values with the corresponding view model properties.

The controller can receive the submitted information as follows:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(ProductEditViewModel input)
{
    if (!ModelState.IsValid)
    {
        return View(input);
    }

    return RedirectToAction("Details",
        new { id = input.Id });
}

This example demonstrates model binding and validation. It does not update a database. A production implementation must retrieve the authorized record, apply permitted changes and save the result before redirecting.

Model binding constructs or populates a model from the incoming request. It does not recover the original object instance that was previously supplied to the Razor view.

Best Methods for Passing Objects from View to Controller

The appropriate method depends on whether the object already exists in a data source, how long the information must remain available, its size, its sensitivity and the reliability requirements of the application.

Method Recommended Use Reliability and Limitations
Pass an ID and retrieve the object Existing database records Reliable while the record remains available; authorization is required.
Server-side draft storage Unsaved records and multi-step workflows Can provide durable recovery and controlled expiration.
Session state Temporary, browser-session-specific information Subject to session expiration and cache availability.
Distributed cache Temporary objects shared across application servers Depends on cache configuration, expiration and eviction policies.
Hidden form fields Small, non-sensitive values Client-controlled and potentially modifiable.
TempData Short-lived messages and redirect information Normally consumed after being read; unsuitable for substantial long-running workflows.
JSON request body JavaScript-based forms and API interactions Requires explicit client-side submission and server-side validation.
ViewData or ViewBag Passing information from a controller to its current view Does not provide storage across independent HTTP requests.

Method 1: Pass an Identifier and Retrieve the Object

Passing an identifier is generally the preferred approach when the object already exists in a database, repository or another authoritative data source.

Instead of submitting every object property, send only the identifier required to locate the record. The receiving controller retrieves the object, verifies that the current user may access it and prepares the appropriate view model.

Step 1: Create the navigation link

@model Product

<a asp-controller="Products"
   asp-action="Edit"
   asp-route-id="@Model.Id"
   class="btn btn-primary">

    Edit Product

</a>

Depending on the routing configuration, the generated URL might resemble either of the following:

/Products/Edit/101

/Products/Edit?id=101

Step 2: Create a dedicated edit view model

using System.ComponentModel.DataAnnotations;

public class ProductEditViewModel
{
    public int Id { get; set; }

    [Required]
    [StringLength(150)]
    public string Name { get; set; } = string.Empty;

    [StringLength(1000)]
    public string Description { get; set; } = string.Empty;
}

The view model contains only the identifier and properties the user is expected to edit.

Step 3: Retrieve the object in the GET action

[HttpGet]
[Authorize]
public async Task<IActionResult> Edit(int id)
{
    var product = await _context.Products.FindAsync(id);

    if (product == null)
    {
        return NotFound();
    }

    var authorization = await _authorizationService
        .AuthorizeAsync(User, product, "EditProduct");

    if (!authorization.Succeeded)
    {
        return Forbid();
    }

    var model = new ProductEditViewModel
    {
        Id = product.Id,
        Name = product.Name,
        Description = product.Description
    };

    return View(model);
}

The example assumes an Entity Framework Core database context named _context, an injected IAuthorizationService instance named _authorizationService, and a registered resource-based authorization policy named EditProduct.

The authorization policy must enforce the application's actual record ownership, tenancy or access-control requirements. These application-specific components must be implemented before the example can be used.

Step 4: Create the editing view

Create or update the Views/Products/Edit.cshtml file:

@model ProductEditViewModel

<form asp-controller="Products"
      asp-action="Edit"
      method="post">

    <div asp-validation-summary="ModelOnly"></div>

    <input asp-for="Id" type="hidden" />

    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name"></span>
    </div>

    <div>
        <label asp-for="Description"></label>
        <textarea asp-for="Description"
                  class="form-control"></textarea>
        <span asp-validation-for="Description"></span>
    </div>

    <button type="submit" class="btn btn-primary">
        Save Changes
    </button>

</form>

Step 5: Receive and process the submitted view model

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(
    ProductEditViewModel input)
{
    if (!ModelState.IsValid)
    {
        return View(input);
    }

    var product = await _context.Products
        .FindAsync(input.Id);

    if (product == null)
    {
        return NotFound();
    }

    var authorization = await _authorizationService
        .AuthorizeAsync(User, product, "EditProduct");

    if (!authorization.Succeeded)
    {
        return Forbid();
    }

    product.Name = input.Name;
    product.Description = input.Description;

    await _context.SaveChangesAsync();

    return RedirectToAction(
        nameof(Details),
        new { id = product.Id });
}

This approach retrieves the existing database entity and updates only the explicitly permitted properties. Properties such as ownership, approval status, internal permissions and other business-controlled values are not copied from the submitted model.

For production applications, also implement appropriate database exception handling and optimistic concurrency protection where simultaneous editing is possible.

Advantages of passing an identifier

  • Reduces the amount of data transmitted between the client and server.
  • Keeps authoritative business information under server control.
  • Avoids exposing unnecessary entity properties.
  • Supports centralized authorization and validation.
  • Works naturally with Entity Framework Core and repository-based applications.
  • Allows the application to retrieve current information rather than relying entirely on previously displayed values.

Limitations

The object must exist in a retrievable data source or be reconstructable from the identifier. An identifier alone cannot recover an object that existed only in memory during a previous request.

Retrieving the latest record can also introduce concurrency considerations if another user changes the same record between the display and editing operations.

Method 2: Use Server-Side Draft Storage for Unsaved Objects

Some applications need to collect, display, review and edit information before committing it to the final database tables.

Common examples include:

  • Purchase order creation.
  • Insurance application processing.
  • Customer onboarding.
  • Invoice preparation.
  • Imported data review.
  • Multi-step registration forms.
  • Business approval workflows.
  • Data verification before updating an external application.

For these scenarios, a dedicated draft store is often more appropriate than immediately creating a completed business record.

A draft store temporarily or durably maintains an object together with its identifier, ownership information, editing status and other metadata required by the workflow.

Recommended draft workflow

  1. Generate or receive the initial information.
  2. Create a unique draft identifier.
  3. Associate the draft with the authenticated user or tenant.
  4. Store the draft in an appropriate server-side data store.
  5. Display a preview of the draft.
  6. Pass the draft identifier to the editing action.
  7. Retrieve and authorize access to the draft.
  8. Display a dedicated editing view model.
  9. Validate and save permitted changes to the draft.
  10. Display a final review or confirmation page.
  11. Commit the approved information to the final business data store.
  12. Mark the draft as completed or remove it according to the application's retention policy.
Generate Object
       |
       v
Create Server-Side Draft
       |
       v
Preview View
       |
       | Draft ID
       v
Controller GET Action
       |
       v
Editing View
       |
       | Submitted ViewModel
       v
Controller POST Action
       |
       v
Validate and Update Draft
       |
       v
Review and Confirmation
       |
       v
Commit Final Business Record

Step 1: Define a draft model

public class ProductDraft
{
    public Guid Id { get; set; } = Guid.NewGuid();

    public string OwnerId { get; set; } = string.Empty;

    public string Name { get; set; } = string.Empty;

    public string Description { get; set; } = string.Empty;

    public DateTimeOffset CreatedUtc { get; set; }
        = DateTimeOffset.UtcNow;

    public DateTimeOffset ExpiresUtc { get; set; }
        = DateTimeOffset.UtcNow.AddHours(24);
}

The draft identifier separates individual editing operations. The owner identifier associates the draft with the user who is permitted to access it.

The 24-hour expiration shown above is an example application policy, not a limitation or default setting imposed by ASP.NET Core MVC.

Step 2: Define a draft storage abstraction

public interface IProductDraftStore
{
    Task SaveAsync(ProductDraft draft);

    Task<ProductDraft?> GetAsync(Guid id);

    Task DeleteAsync(Guid id);
}

The interface separates the controller from the underlying storage mechanism. Depending on the application's requirements, it can be implemented using a database, distributed cache or another suitable server-side storage service.

A concrete implementation must be registered with the application's dependency injection container. The interface alone does not store data.

Step 3: Create the draft and display its preview

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateDraft(
    ProductEditViewModel input)
{
    if (!ModelState.IsValid)
    {
        return View("Create", input);
    }

    var userId = User.FindFirst(
        ClaimTypes.NameIdentifier)?.Value;

    if (string.IsNullOrEmpty(userId))
    {
        return Forbid();
    }

    var draft = new ProductDraft
    {
        OwnerId = userId,
        Name = input.Name,
        Description = input.Description
    };

    await _draftStore.SaveAsync(draft);

    return RedirectToAction(
        nameof(Preview),
        new { id = draft.Id });
}

This example assumes that the application uses authentication with a stable user identifier claim, that System.Security.Claims is imported and that _draftStore is an injected implementation of IProductDraftStore.

The corresponding preview action retrieves the draft:

[HttpGet]
[Authorize]
public async Task<IActionResult> Preview(Guid id)
{
    var userId = User.FindFirst(
        ClaimTypes.NameIdentifier)?.Value;

    if (string.IsNullOrEmpty(userId))
    {
        return Forbid();
    }

    var draft = await _draftStore.GetAsync(id);

    if (draft == null ||
        draft.OwnerId != userId ||
        draft.ExpiresUtc <= DateTimeOffset.UtcNow)
    {
        return NotFound();
    }

    return View(draft);
}

Returning NotFound() for an inaccessible draft is one possible application design that avoids revealing whether another user's draft exists.

Step 4: Pass the draft identifier between views

The preview view displays the information without providing editable controls:

@model ProductDraft

<h2>Product Preview</h2>

<p>@Model.Name</p>
<p>@Model.Description</p>

<a asp-controller="Products"
   asp-action="Manual"
   asp-route-id="@Model.Id"
   class="btn btn-primary">

    Manual Edit

</a>

No editable input fields are necessary in this view because the draft already exists on the server. The navigation link transfers only its identifier.

Step 5: Create a dedicated draft editing view model

using System.ComponentModel.DataAnnotations;

public class ManualEditViewModel
{
    public Guid DraftId { get; set; }

    [Required]
    [StringLength(150)]
    public string Name { get; set; } = string.Empty;

    [StringLength(1000)]
    public string Description { get; set; } = string.Empty;
}

Step 6: Retrieve the draft in the editing action

[HttpGet]
[Authorize]
public async Task<IActionResult> Manual(Guid id)
{
    var userId = User.FindFirst(
        ClaimTypes.NameIdentifier)?.Value;

    if (string.IsNullOrEmpty(userId))
    {
        return Forbid();
    }

    var draft = await _draftStore.GetAsync(id);

    if (draft == null ||
        draft.OwnerId != userId ||
        draft.ExpiresUtc <= DateTimeOffset.UtcNow)
    {
        return NotFound();
    }

    var model = new ManualEditViewModel
    {
        DraftId = draft.Id,
        Name = draft.Name,
        Description = draft.Description
    };

    return View(model);
}

Step 7: Display the manual editing view

@model ManualEditViewModel

<form asp-controller="Products"
      asp-action="Manual"
      method="post">

    <div asp-validation-summary="ModelOnly"></div>

    <input asp-for="DraftId" type="hidden" />

    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name"></span>
    </div>

    <div>
        <label asp-for="Description"></label>
        <textarea asp-for="Description"
                  class="form-control"></textarea>
        <span asp-validation-for="Description"></span>
    </div>

    <button type="submit" class="btn btn-primary">
        Continue
    </button>

</form>

Step 8: Update the draft without committing the final record

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Manual(
    ManualEditViewModel input)
{
    var userId = User.FindFirst(
        ClaimTypes.NameIdentifier)?.Value;

    if (string.IsNullOrEmpty(userId))
    {
        return Forbid();
    }

    var draft = await _draftStore.GetAsync(
        input.DraftId);

    if (draft == null ||
        draft.OwnerId != userId ||
        draft.ExpiresUtc <= DateTimeOffset.UtcNow)
    {
        return NotFound();
    }

    if (!ModelState.IsValid)
    {
        return View(input);
    }

    draft.Name = input.Name;
    draft.Description = input.Description;

    await _draftStore.SaveAsync(draft);

    return RedirectToAction(
        nameof(Preview),
        new { id = draft.Id });
}

The updated object remains in the draft store. The final business record has not yet been committed.

This design allows users to move between preview and editing pages without transmitting the complete object through every request.

Step 9: Commit the draft after final confirmation

The final confirmation operation should use an authorized HTTP POST action protected by antiforgery validation.

Before committing the draft, the application should:

  • Retrieve the current draft from its server-side store.
  • Verify the authenticated user's access rights.
  • Check whether the draft has expired or has already been completed.
  • Validate the complete business object again.
  • Check applicable concurrency and business constraints.
  • Persist the final record.
  • Mark the draft as completed or arrange safe cleanup.
  • Redirect to a confirmation or details page.

Where the final record and draft are maintained in the same transactional database, consider committing the record and marking the draft as completed within a single database transaction.

If the draft and destination use different storage systems, a single Entity Framework Core transaction cannot automatically guarantee atomic changes across both. Use an appropriate idempotency and recovery design to prevent duplicate submissions or inconsistent completion states.

Advantages of server-side draft storage

  • Supports objects that have not become final business records.
  • Allows flexible navigation between editing and preview pages.
  • Supports multiple simultaneous drafts for the same user.
  • Reduces client-side exposure of internal properties.
  • Can provide recovery after browser closure or application restarts when durable storage is used.
  • Separates incomplete information from approved production records.
  • Supports expiration, auditing, ownership and workflow management.

Important: Saving an object into a draft database or persistent storage service is still a form of data persistence. It is different from committing the final business record, but it does not satisfy a requirement that absolutely no information may be written to persistent storage before confirmation.

Method 3: Pass Complex Objects Using Session State

ASP.NET Core session state provides temporary server-side storage associated with a browser session. The browser uses a session identifier cookie, while the application retrieves the corresponding information from its configured session store.

Session state can be useful when an object needs to remain available for a short editing workflow without becoming a permanent database record.

Prerequisites

  • An ASP.NET Core MVC application using the modern hosting model.
  • A configured session service and cache implementation.
  • Session middleware enabled in the HTTP request pipeline.
  • Browser cookies available under the application's cookie and consent configuration.

No operating system administrator privileges are required to modify the application source code. Appropriate deployment permissions are necessary when publishing changes to an existing environment.

Step 1: Configure session state in Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

builder.Services.AddDistributedMemoryCache();

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);

    options.Cookie.HttpOnly = true;

    options.Cookie.SecurePolicy =
        CookieSecurePolicy.Always;
});

var app = builder.Build();

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseSession();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

This example uses an in-process implementation of the distributed cache interface. Despite its name, AddDistributedMemoryCache() does not share cached information across separate application instances.

For an existing authenticated application, retain its authentication configuration and middleware. Session state is not a replacement for authentication or authorization.

The secure cookie setting assumes the application is accessed over HTTPS. The session idle timeout of 30 minutes is an example configuration rather than the framework's default.

The session cookie should be classified and configured according to the application's actual privacy and consent requirements. Do not mark cookies as essential solely to bypass consent restrictions.

Step 2: Create JSON serialization helpers

Complex objects must be converted into a format suitable for session storage. The following extension methods use System.Text.Json:

using Microsoft.AspNetCore.Http;
using System.Text.Json;

public static class SessionExtensions
{
    public static void SetObject<T>(
        this ISession session,
        string key,
        T value)
    {
        var json = JsonSerializer.Serialize(value);

        session.SetString(key, json);
    }

    public static T? GetObject<T>(
        this ISession session,
        string key) where T : class
    {
        var json = session.GetString(key);

        return json == null
            ? null
            : JsonSerializer.Deserialize<T>(json);
    }
}

Use simple data models that are suitable for serialization. Avoid storing live Entity Framework Core tracking objects, database connections, service instances, credentials or unnecessarily large object graphs.

Step 3: Save an object into session

var draft = new ProductDraft
{
    OwnerId = userId,
    Name = "Wireless Keyboard",
    Description = "USB wireless keyboard"
};

await HttpContext.Session.LoadAsync();

HttpContext.Session.SetObject(
    $"ProductDraft:{draft.Id}",
    draft);

In an authenticated workflow, the variable userId must come from the current authenticated identity, not from an untrusted form field.

Using a draft-specific session key allows the application to distinguish multiple drafts instead of overwriting a single fixed session entry.

Step 4: Pass the draft identifier from the view

@model ProductDraft

<a asp-action="Manual"
   asp-route-id="@Model.Id">

    Edit Draft

</a>

Step 5: Retrieve the draft from session

[HttpGet]
[Authorize]
public async Task<IActionResult> Manual(Guid id)
{
    var userId = User.FindFirst(
        ClaimTypes.NameIdentifier)?.Value;

    if (string.IsNullOrEmpty(userId))
    {
        return Forbid();
    }

    await HttpContext.Session.LoadAsync();

    var draft = HttpContext.Session
        .GetObject<ProductDraft>(
            $"ProductDraft:{id}");

    if (draft == null ||
        draft.OwnerId != userId ||
        draft.ExpiresUtc <= DateTimeOffset.UtcNow)
    {
        return NotFound();
    }

    return View(new ManualEditViewModel
    {
        DraftId = draft.Id,
        Name = draft.Name,
        Description = draft.Description
    });
}

Step 6: Update and remove session information

After retrieving, authorizing and validating the draft, update the permitted properties and write the modified object back into session.

draft.Name = input.Name;
draft.Description = input.Description;

HttpContext.Session.SetObject(
    $"ProductDraft:{draft.Id}",
    draft);

After the workflow is successfully completed, the individual draft entry can be removed:

HttpContext.Session.Remove(
    $"ProductDraft:{draft.Id}");

Avoid clearing the entire session merely to remove a completed draft, because other application features may depend on unrelated session entries.

Limitations of session state

  • Sessions can expire during inactivity.
  • Users may lose access when browser cookies are removed or become unavailable.
  • In-memory session information can be lost during application restarts.
  • Session data is not designed to be the sole durable copy of important business information.
  • Large serialized objects increase memory, storage and processing requirements.
  • Concurrent requests can overwrite session changes because ASP.NET Core session state does not provide per-session locking for concurrent updates.
  • Multi-server environments require suitable shared session storage or another deployment strategy.

A unique session key helps distinguish drafts across browser tabs, but it does not eliminate concurrent session-write conflicts.

Microsoft documents session data as temporary application state. Important information that must survive session failure should be maintained in an appropriate durable data store.

Method 4: Use Distributed Cache for Temporary Objects

A distributed cache provides temporary storage that can be accessed by multiple application instances when configured with a genuinely shared backend.

This approach is particularly relevant to ASP.NET Core applications deployed across multiple web servers, containers or cloud application instances.

Depending on the application and installed packages, distributed cache implementations may use services such as:

  • Redis.
  • Microsoft SQL Server.
  • PostgreSQL.
  • Other implementations of the IDistributedCache interface.

Objects are generally serialized before storage and deserialized when retrieved.

Example distributed cache draft store

using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;

public class CachedProductDraftStore
    : IProductDraftStore
{
    private readonly IDistributedCache _cache;

    public CachedProductDraftStore(
        IDistributedCache cache)
    {
        _cache = cache;
    }

    private static string GetKey(Guid id)
    {
        return $"ProductDraft:{id}";
    }

    public async Task SaveAsync(ProductDraft draft)
    {
        if (draft.ExpiresUtc <= DateTimeOffset.UtcNow)
        {
            throw new InvalidOperationException(
                "The draft has expired.");
        }

        var json = JsonSerializer.Serialize(draft);

        var options =
            new DistributedCacheEntryOptions
            {
                AbsoluteExpiration = draft.ExpiresUtc
            };

        await _cache.SetStringAsync(
            GetKey(draft.Id),
            json,
            options);
    }

    public async Task<ProductDraft?> GetAsync(Guid id)
    {
        var json = await _cache.GetStringAsync(
            GetKey(id));

        return json == null
            ? null
            : JsonSerializer
                .Deserialize<ProductDraft>(json);
    }

    public Task DeleteAsync(Guid id)
    {
        return _cache.RemoveAsync(GetKey(id));
    }
}

Register the draft-store implementation after configuring an appropriate IDistributedCache provider:

builder.Services.AddScoped
    <IProductDraftStore, CachedProductDraftStore>();

The chosen cache provider must be configured separately. The storage class does not establish a Redis, SQL Server or PostgreSQL connection by itself.

When distributed cache is appropriate

  • The information is temporary and can tolerate occasional loss.
  • The application runs across multiple server instances.
  • The workflow requires independent draft identifiers.
  • Automatic expiration is desirable.
  • Temporary objects may need to be accessed independently of a specific browser session.

Important limitations

A distributed cache is not automatically a durable database. Information may disappear because of expiration, eviction, service outages, administrative actions or backend-specific persistence settings.

The example is suitable for demonstrating temporary draft storage but does not provide atomic concurrent updates, production-grade retry handling or guaranteed durability.

Use a durable draft database when losing an incomplete object would cause significant business disruption.

Method 5: Pass Object Properties Using Hidden Fields

Hidden form fields allow property values to be submitted without displaying editable controls to the user.

This method can be suitable when the object is small and the required information can safely be sent to the browser.

Example Razor view

@model ProductEditViewModel

<h2>Product Preview</h2>

<p>@Model.Name</p>
<p>@Model.Description</p>

<form asp-controller="Products"
      asp-action="ManualFromPreview"
      method="post">

    <input asp-for="Id" type="hidden" />
    <input asp-for="Name" type="hidden" />
    <input asp-for="Description" type="hidden" />

    <button type="submit" class="btn btn-primary">
        Manual Edit
    </button>

</form>

Receiving controller action

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public IActionResult ManualFromPreview(
    ProductEditViewModel input)
{
    return View("Edit", input);
}

The submitted view model is used to render the editing page. The editing view should display applicable validation errors and allow users to correct invalid values before completing the workflow.

No database operation is performed by this example.

Security warning about hidden fields

Hidden fields are not secure storage. Their values can be inspected and modified using browser developer tools, custom HTTP clients or other client-side mechanisms.

Do not rely on hidden fields as authoritative sources for values such as:

  • User roles and permissions.
  • Product prices controlled by the server.
  • Account balances.
  • Financial approval status.
  • Record ownership.
  • Internal access-control decisions.
  • Passwords, API credentials and private keys.
  • Business-sensitive information that the user is not authorized to receive.

Hidden identifiers are commonly used to locate records, but the server must independently confirm that the current user may access the identified record.

Antiforgery validation does not prevent an authorized user from modifying hidden field values. Business validation and resource-level authorization remain necessary.

Advantages

  • Simple implementation.
  • No additional server-side draft-storage infrastructure.
  • Works with standard MVC form model binding.
  • Allows non-editable preview pages to submit selected properties.

Disadvantages

  • Property values are exposed to the client.
  • Submitted information can be manipulated.
  • Large models increase response and request sizes.
  • Complex nested objects and collections require correctly structured field names.
  • Previously displayed values may become outdated.
  • Long workflows can require repeatedly submitting the same information.

Hidden fields are best reserved for limited client-round-trip information rather than entire business entities.

Method 6: Use TempData for Short-Lived Information

TempData is an ASP.NET Core MVC feature intended for transferring small amounts of temporary information between requests, particularly during redirects.

It is commonly used for success messages, notifications and workflow feedback.

Example

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CompleteOperation()
{
    TempData["SuccessMessage"] =
        "The operation was completed successfully.";

    return RedirectToAction(nameof(Index));
}

The destination Razor view can display the message:

@if (TempData["SuccessMessage"] is string message)
{
    <div class="alert alert-success">
        @message
    </div>
}

By default, ASP.NET Core MVC uses a cookie-based TempData provider. A session-based provider can be configured when appropriate.

Reading a TempData entry normally marks it for removal. The Peek() and Keep() methods can preserve entries for additional requests.

Although a simple object can be serialized into a string for TempData storage, this does not make TempData an appropriate general-purpose draft repository.

Cookie-based TempData is subject to browser cookie limits and request overhead. Session-based TempData inherits the relevant session-storage limitations.

Best practice: Use TempData for operation messages and small redirect-related values rather than substantial editable objects.

Method 7: Submit Object Data as JSON

Applications with JavaScript-driven interfaces can explicitly serialize selected object properties into JSON and submit them to a controller or API endpoint.

The receiving endpoint can use the [FromBody] attribute to bind the request body to a suitable view model or data transfer object.

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public IActionResult ReceiveProduct(
    [FromBody] ProductEditViewModel input)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    return Ok(new
    {
        Received = true,
        ProductId = input.Id
    });
}

The client must explicitly send a request with an appropriate JSON content type and a body resembling the following:

{
    "id": 101,
    "name": "Wireless Keyboard",
    "description": "USB wireless keyboard"
}

This example demonstrates JSON deserialization and validation. It does not modify a database or persist the received object.

When an endpoint is protected by antiforgery validation, the client must also supply the appropriate antiforgery token according to the application's configured header or request-handling mechanism.

For API architectures that use different authentication mechanisms, security and antiforgery requirements must be evaluated according to the application's actual request model.

JSON submission provides flexibility for dynamic interfaces, but it does not change the fundamental rule that client-supplied data must be treated as untrusted.

Using Multiple Submit Buttons to Call Different Controller Actions

A common requirement is to provide two operations in a preview view:

  • Open another view for manual editing.
  • Submit the current information for final processing.

If both operations must submit the same form fields, ASP.NET Core MVC provides the Form Action Tag Helper.

@model ProductEditViewModel

<form asp-controller="Products"
      asp-action="Update_DB"
      method="post">

    <input asp-for="Id" type="hidden" />
    <input asp-for="Name" type="hidden" />
    <input asp-for="Description" type="hidden" />

    <button type="submit"
            asp-controller="Products"
            asp-action="ManualFromPreview"
            class="btn btn-primary">

        Manual Edit

    </button>

    <button type="submit"
            class="btn btn-warning">

        Update Database

    </button>

</form>

The first button generates a button-specific form destination. The second button uses the destination configured on the surrounding form.

Both buttons submit the applicable named form controls. The receiving actions must accept the corresponding HTTP method and implement appropriate validation and authorization.

This is useful when both operations require submitted data. When manual editing requires only navigation to an existing server-side draft, a regular GET link carrying the draft identifier is simpler.

Recommended Solution for Editing an Object Before Database Persistence

When an application needs to display an object in one view, offer manual editing in another view and postpone the final database operation, the recommended design is to maintain the object in a server-side draft store.

The preview view can then pass only the draft identifier to the appropriate controller action.

@model ProductDraft

<form asp-controller="Home"
      asp-action="Update_DB"
      method="post">

    <input type="hidden"
           name="id"
           value="@Model.Id" />

    <a asp-controller="Home"
       asp-action="Manual"
       asp-route-id="@Model.Id"
       class="btn btn-primary">

        Manual

    </a>

    <button type="submit"
            class="btn btn-warning">

        Update Database

    </button>

</form>

The Manual link sends the draft identifier through an HTTP GET request. The Update Database button sends the identifier through an HTTP POST request.

Both receiving actions retrieve the relevant draft from server-side storage and independently verify that the current user is authorized to access it.

Operation HTTP Method Request Data Server Responsibility
Open manual editing GET Draft identifier Retrieve and authorize the draft, then display the editing view.
Save manual changes POST Draft identifier and editable properties Validate the request and update permitted draft properties.
Display final preview GET Draft identifier Retrieve and display the current authorized draft.
Update the database POST Draft identifier Validate the authoritative draft and commit the approved business record.

If the operation involves an irreversible or business-critical external update, provide a confirmation mechanism appropriate to the application's requirements before committing the information.

This architecture avoids repeatedly transferring the complete object and allows the first view to remain a read-only preview.

What If the Object Must Never Be Persisted Before Editing?

Some applications have a specific requirement that the intermediate object must not be written to a database or another persistent storage system before the user confirms the operation.

Under this restriction, the available approaches are limited to maintaining or reconstructing the data through another permitted mechanism.

Approach Intermediate Data Location Principal Limitation
In-memory session Application process memory Information may disappear after expiration or restart.
Non-persistent shared cache Shared cache memory Requires verified backend persistence and eviction settings.
Hidden form fields Browser and HTTP requests Information is exposed to the client and can be modified.
Reconstruction from source information Existing authoritative source Only possible when sufficient source information remains available.
Single-page editing Current browser page Unsaved information may disappear when the page is closed or refreshed.

It is not possible for a subsequent HTTP request to recover an arbitrary object from a previous request if the object was discarded, cannot be reconstructed and is not represented anywhere in the new request or accessible storage.

The application must choose an acceptable balance between temporary storage, client-side state, reliability and data-loss tolerance.

If the restriction is driven by confidentiality or regulatory requirements, also evaluate whether caches, browser storage, logs, backups and infrastructure services retain copies of the information.

Use View Models Instead of Direct Entity Binding

One of the most important security practices in ASP.NET Core MVC is to avoid using broad database entity classes as unrestricted input models for editing operations.

Consider an entity containing both editable information and internal business properties:

public class Product
{
    public int Id { get; set; }

    public string Name { get; set; } = string.Empty;

    public string Description { get; set; } = string.Empty;

    public decimal ApprovedPrice { get; set; }

    public bool IsApproved { get; set; }

    public string OwnerId { get; set; } = string.Empty;
}

If an action accepts the entire entity, properties included in an unexpected or manipulated request may be bound even when the original editing view did not display controls for those properties.

This issue is commonly known as overposting or mass assignment.

Accept a dedicated view model containing only the intended input fields:

public class ProductEditViewModel
{
    public int Id { get; set; }

    public string Name { get; set; } = string.Empty;

    public string Description { get; set; } = string.Empty;
}

After validating the view model and retrieving the authorized database entity, explicitly assign the permitted values:

product.Name = input.Name;
product.Description = input.Description;

The application retains control over the approved price, approval status and ownership information.

Microsoft's model-binding and Entity Framework Core MVC documentation recommends using dedicated view models as an effective way to reduce overposting risks, especially during edit operations.

Why Static Variables and Singleton Objects Should Not Store User Drafts

A controller's instance fields should not be treated as storage that automatically survives navigation between independent HTTP requests.

Under the normal MVC controller activation model, a later request generally uses a different controller instance. A field populated during a previous request therefore cannot be relied upon to contain the earlier object's values.

Making the field static does not provide a safe solution.

Static fields belong to the application process and can be shared by requests from different users. Storing a current user's object in a shared static field can result in data being overwritten, unintended cross-user access and unpredictable behaviour under concurrent requests.

Similar problems can occur when a singleton service retains a single mutable object representing the current user's workflow.

Singleton services may legitimately manage thread-safe shared infrastructure, but user-specific objects require explicit isolation, authorization, expiration and concurrency management.

Use session state, an appropriately designed cache or a dedicated draft repository rather than an unprotected static or singleton field.

ViewData, ViewBag, TempData and Session: Key Differences

Feature Scope Typical Use Suitable for Long-Running Drafts?
ViewData Current request and view rendering Supplementary display information No
ViewBag Current request and view rendering Dynamic access to supplementary view information No
TempData Across requests until consumed or otherwise removed Redirect messages and limited transient data Generally no
Session Associated browser session Temporary workflow state Only when expiration and possible loss are acceptable
Distributed cache Determined by cache keys and backend availability Shared temporary application data Conditional on reliability requirements
Database draft store Defined by application retention and authorization policies Recoverable drafts and business workflows Yes

Security Best Practices

1. Treat all incoming values as untrusted

Route values, query-string parameters, hidden fields and JSON request bodies can be modified by the client. Validate incoming information regardless of how the original page was generated.

2. Verify authorization for each object

Authentication identifies the user, but it does not automatically grant access to every record or draft.

Verify that the authenticated user has permission to access and modify the particular object identified by the request.

This protects against unauthorized access to records through manipulated identifiers, commonly associated with insecure direct object references or broken object-level authorization.

3. Use appropriate antiforgery protection

For conventional cookie-authenticated MVC form workflows, protect state-changing operations against cross-site request forgery using the framework's antiforgery facilities.

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Save(ProductEditViewModel input)
{
    if (!ModelState.IsValid)
    {
        return View(input);
    }

    return Ok();
}

The Form Tag Helper normally generates the required antiforgery field for eligible POST forms.

Apply authorization and business validation separately. Antiforgery validation does not replace either requirement.

4. Perform server-side model validation

Use validation attributes and application-specific rules to verify required values, string lengths, numeric ranges and business constraints.

if (!ModelState.IsValid)
{
    return View(input);
}

Client-side validation improves the user experience but must not replace server-side validation.

5. Avoid sensitive information in URLs

URLs can appear in browser history, application logs, reverse proxy logs, analytics services and other infrastructure.

Use only the information required for navigation. Do not place passwords, complete confidential objects, private credentials or sensitive personal information in route or query-string values.

A random draft identifier can make enumeration more difficult, but it is not a substitute for authorization and should not automatically be treated as a secret access token.

6. Configure draft expiration and cleanup

Define how long incomplete drafts must remain available. Expired or abandoned drafts should be handled according to the application's operational, privacy and retention requirements.

Cache providers may automatically remove expired entries. Database-backed drafts require an appropriate cleanup or archival strategy.

7. Use HTTPS

HTTPS protects information transmitted between the browser and application against network-level interception and modification.

HTTPS does not prevent the browser user from inspecting or changing information that the application deliberately sends to that browser.

8. Implement concurrency protection

Users may open the same editing page in multiple tabs, or multiple authorized users may modify the same business record.

For workflows where these situations matter, use version identifiers, concurrency tokens or appropriate atomic update mechanisms to detect conflicting changes.

Entity Framework Core supports optimistic concurrency through configured concurrency tokens. When a conflicting database update is detected, the application can handle the resulting DbUpdateConcurrencyException.

9. Prevent accidental duplicate submissions

Users may refresh a page, double-click a button or retry an operation after a network interruption.

Use the Post-Redirect-Get pattern after successful submissions to reduce accidental form resubmission during normal navigation.

For final operations that must execute only once, implement server-side idempotency, appropriate uniqueness constraints and completion-state checks. Redirecting after a POST does not independently guarantee duplicate prevention.

Common Mistakes and Recommended Corrections

Common Mistake Recommended Correction
Expecting the Razor @model directive to submit the entire object. Explicitly submit selected fields or pass an identifier to a server-side object.
Using an anchor element to submit form values. Use a submit button or pass appropriate navigation parameters through the anchor.
Storing the current user's object in a static variable. Use isolated session state or a server-side draft repository.
Binding a complete database entity during an edit operation. Accept a dedicated input model and explicitly update permitted properties.
Trusting hidden field values. Validate submitted values and obtain authoritative information from the server.
Using ViewBag to transfer data across redirects. Use route parameters, TempData, session or server-side storage according to the use case.
Storing important long-running drafts only in session. Use durable storage when recovery and reliability are required.
Checking authentication without verifying object access. Implement resource-specific ownership or authorization checks.
Performing database updates through an HTTP GET request. Use an appropriate state-changing HTTP method with applicable request protection.
Ignoring concurrent edits and duplicate requests. Implement concurrency handling and server-side duplicate prevention where required.

Troubleshooting Model Binding Problems

Problem 1: The controller receives an empty or default model

Possible causes include missing named form controls, incorrect field names, disabled form controls, an incorrect binding source or a request that does not contain the expected information.

To investigate:

  1. Open the page in a browser.
  2. Open the browser's developer tools.
  3. Select the Network panel.
  4. Submit the form.
  5. Inspect the destination URL and HTTP request method.
  6. Examine the request's form data, query parameters or JSON payload.
  7. Compare the submitted field names with the receiving model properties.
  8. Check the controller's action parameters and binding attributes.
  9. Inspect ModelState for binding and validation errors using a development debugger.

If the expected property values are absent from the request, the problem is usually related to form generation or submission rather than the controller's database code.

Problem 2: Clicking the Manual link does not send form values

A normal anchor generates navigation rather than form submission.

If the target action only requires an identifier, add the corresponding route value:

<a asp-action="Manual"
   asp-route-id="@Model.Id">
    Manual
</a>

If the target action requires the current form values, use a submit button with the appropriate Form Action Tag Helper configuration.

Problem 3: Hidden fields are not being bound

Inspect the generated HTML and confirm that each required field has the correct name attribute.

For example:

<input type="hidden"
       name="Id"
       value="101" />

An HTML id attribute alone does not determine a form field's submitted name.

Also confirm that the field belongs to the submitted form, is not disabled and uses a naming structure compatible with the expected model.

Problem 4: Tag Helpers are not generating the expected HTML

Check whether the appropriate _ViewImports.cshtml file enables ASP.NET Core MVC Tag Helpers.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Inspect the final browser-rendered HTML rather than assuming the Razor attributes were processed correctly.

Problem 5: Session values disappear

Investigate the following possible causes:

  • Session idle timeout has elapsed.
  • The session cookie is missing or unavailable.
  • Cookie consent or security settings prevent the expected session behaviour.
  • The application process restarted while using in-memory storage.
  • Multiple server instances are using separate local caches.
  • The application retrieved the wrong session key.
  • A concurrent request overwrote session changes.
  • The underlying cache service failed or removed the entry.

Verify service registration, middleware ordering, cache connectivity and browser cookie behaviour before increasing timeout settings or changing the storage architecture.

Problem 6: The request returns HTTP 400

A bad-request response during form submission can result from antiforgery validation failure, invalid request formatting or other application-specific validation mechanisms.

Check whether the expected antiforgery field or configured header was submitted and whether the request contains the appropriate content type.

Review development or application logs to identify the actual cause. Do not permanently disable antiforgery protection merely to suppress the error.

Problem 7: The request returns HTTP 404 or HTTP 405

HTTP 404 may indicate an unmatched route, an unavailable object or an intentional not-found response used by the application for inaccessible resources.

HTTP 405 generally indicates that the HTTP method used by the request is not supported by the matched endpoint.

Verify the controller name, action name, route parameters, endpoint mapping and action attributes such as [HttpGet] and [HttpPost].

Problem 8: Editing one browser tab changes another draft

This can occur when the application stores every editing operation under a single fixed key such as CurrentProduct.

Assign each draft a unique identifier and make that identifier part of its storage key.

ProductDraft:550e8400-e29b-41d4-a716-446655440000

For workflows with concurrent writes, also implement appropriate versioning or storage-level concurrency protection.

How to Verify the Recommended Implementation

Before deploying a draft-based editing workflow to a production application, test the complete request sequence in a development or staging environment.

Test Scenario Expected Result
Open the preview page. The correct draft information is displayed.
Click Manual Edit. The editing page retrieves the same authorized draft.
Modify permitted properties. Only the permitted draft properties are updated.
Submit an invalid required field. The request is rejected or redisplayed with appropriate validation feedback.
Open another user's draft identifier. Unauthorized access is denied without exposing the draft's content.
Submit unexpected entity properties. Server-controlled properties remain unchanged.
Open an expired draft. The application handles expiration safely and provides an appropriate recovery path.
Open two different drafts in separate tabs. Each editing operation maintains its own draft identity.
Submit a protected form without a valid antiforgery token. The protected operation is rejected.
Retry the final confirmation request. Duplicate business records are prevented when the required idempotency safeguards are implemented.
Restart the application during editing. The workflow behaves according to the selected storage mechanism's durability guarantees.
Complete the final confirmation. The validated business record is committed and the draft is completed or safely removed.

For database-backed or externally integrated applications, use test records and non-production destinations when verifying final submission behaviour.

Which Method Should You Choose?

Application Requirement Recommended Approach
Edit an existing database record. Pass the record ID and retrieve the authorized entity.
Edit an object before creating the final database record. Use a server-side draft store and pass a draft ID.
Maintain temporary information during a short workflow. Use session state when temporary loss is acceptable.
Maintain temporary drafts across application servers. Use a shared distributed cache or database-backed draft store.
Support long-running or recoverable workflows. Use durable database-backed draft storage.
Transfer a few non-sensitive properties without server-side storage. Use hidden form fields with server-side validation.
Display a message after redirecting. Use TempData.
Submit information from a JavaScript-driven interface. Use a JSON request body and a dedicated input model.
Transfer confidential or authoritative business information. Maintain the information server-side and pass only necessary identifiers and permitted input values.
Prevent permanent storage before confirmation. Use an explicitly permitted temporary mechanism or reconstruct the object from its source.

Frequently Asked Questions

Can ASP.NET Core MVC automatically pass the complete Razor model back to the controller?

No. The Razor model is used to generate the response. A subsequent controller action receives information supplied by the new HTTP request or obtained from accessible application storage and services.

Can I pass an object from one view to another without using a controller?

Partial views can receive model data during the same server-side rendering operation. However, navigation to another MVC page normally involves a new HTTP request handled by an appropriate endpoint. The required data must be submitted, retrieved, reconstructed or maintained through another state-management mechanism.

Can I pass an entire object using asp-route?

Route Tag Helpers generate URL values. They do not automatically serialize and reconstruct arbitrary complex .NET objects.

Although an application could explicitly serialize information into a URL-compatible format, this is generally unsuitable for large, sensitive or authoritative business objects because of URL size, exposure and integrity considerations.

Is it mandatory to use hidden fields when a view has no editable controls?

No. If the required object is available in a server-side store, a navigation link containing its identifier may be sufficient.

Hidden fields are necessary only when specific values must participate in form submission and are not otherwise included through an appropriate request mechanism.

Can an action return another view directly using the submitted object?

Yes. A controller can return a different view and supply a view model within the current request.

return View("Manual", input);

However, returning a view does not create durable state for future requests. Any later submission or navigation still requires explicit data transfer or storage.

Does RedirectToAction transfer the entire model?

No. RedirectToAction() creates a redirect response and can include route values in the destination URL. It does not preserve the original CLR object instance.

For complex information, store the data appropriately and redirect using an identifier.

Can Entity Framework Core retain the object between requests?

A normally configured Entity Framework Core DbContext is scoped to a request. Its tracked entities are not intended to act as shared application state across independent requests.

Retrieve existing entities in the appropriate request and avoid keeping a database context alive merely to preserve an editing workflow.

Is session better than a database for temporary objects?

Session is suitable for short-lived information that can tolerate expiration or loss. Database-backed draft storage is more appropriate when drafts must survive restarts, support recovery, maintain an audit history or remain available for extended periods.

Can a GUID prevent unauthorized draft access?

A randomly generated GUID makes draft identifiers less predictable, but it does not independently establish authorization. Always check whether the current user is permitted to access the identified draft.

Does using a draft table mean I am saving the data before final confirmation?

Yes. A draft table persists intermediate information. The distinction is that the information remains an incomplete draft rather than an approved final business record.

If intermediate persistence is prohibited, select another permitted storage or reconstruction strategy.

What is the best approach for an application hosted on multiple servers?

Use a shared storage mechanism that is accessible to the participating application instances. For recoverable business workflows, a database-backed draft repository is generally preferable. For temporary information that can tolerate loss, a shared distributed cache may be appropriate.

Should I serialize an entire Entity Framework Core entity into session?

It is generally preferable to serialize a purpose-built data model containing only the information required by the workflow. Entity navigation properties, tracking-related behaviour and large object graphs can make serialization more complicated and inefficient.

Applicability and Implementation Notes

The concepts in this article apply to controller-based ASP.NET Core MVC applications using Razor views, standard model binding and modern ASP.NET Core hosting conventions.

The examples focus on contemporary ASP.NET Core MVC development and should not be confused with the legacy ASP.NET MVC framework based on System.Web.

The examples assume that MVC services, routing, Razor Tag Helpers, dependency injection and relevant authentication services are correctly configured.

Application-specific classes, database contexts, authorization policies, draft repositories, routes and final business operations must be integrated into the target application. Select the required NuGet packages according to the actual framework version and storage provider.

The code examples are illustrative implementations based on documented ASP.NET Core and Entity Framework Core behaviour. They have not been compiled or executed as a complete application in a target environment. The database and distributed cache storage designs, example expiration periods and workflow structure should be reviewed against the application's actual security, reliability and business requirements before production deployment.

Key Takeaways

  • The Razor @model directive does not automatically transfer a complete object back to a controller.
  • Model binding obtains values from incoming request information rather than the previous server-side object instance.
  • Pass an identifier whenever the object can be retrieved from an authoritative data source.
  • Use server-side draft storage for substantial multi-step editing workflows.
  • Use session only when temporary storage and potential data loss are acceptable.
  • Use hidden fields for limited client-round-trip information, not confidential or authoritative business values.
  • Use dedicated view models to reduce overposting risks.
  • Use resource-level authorization, server-side validation and appropriate antiforgery protection.
  • Avoid unprotected static fields and shared mutable user-specific objects.
  • Handle concurrency, expiration, recovery and duplicate submissions according to the application's requirements.

For a workflow that displays generated information in one view and allows manual editing in another before committing a final record, the preferred architecture is to create a server-side draft, pass its unique identifier between controller actions, update permitted properties through dedicated view models and complete the final persistence operation only after successful validation and authorization.

Official References

The following Microsoft documentation provides the technical foundation for model binding, form submission, application state management, authorization and secure database editing in ASP.NET Core MVC.

YOUR FEEDBACK

Was this guide useful?

Your answer helps us keep BISONKB accurate and practical.

Links are permitted only to published BISONKB articles.