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

ASP.Net MVC视图传ViewModel至控制器时始终为null求助

Hey there, let's break down why your ViewModel might be showing up as null both in your jQuery variable and when passed to the controller. Here are the most common issues to check:

1. Mismatched Property Names Between ViewModel and Frontend Data

The property names in your backend ViewModel class must exactly match the ones in the object you construct in jQuery (this is case-sensitive!). A tiny typo here will break model binding entirely.

For example, if your ViewModel looks like this:

public class UserViewModel
{
    public string FullName { get; set; }
    public int UserAge { get; set; }
}

Your jQuery object needs to mirror those names perfectly:

var viewModel = {
    FullName: $("#fullNameInput").val(),
    UserAge: parseInt($("#ageInput").val())
};

If you write fullName instead of FullName in your JS, the model binder won't map the value, leading to a null object.

2. Incorrect AJAX Request Configuration

When sending data via jQuery's $.ajax, two key settings are non-negotiable for JSON payloads:

  • Set contentType: "application/json; charset=utf-8" to tell the server you're sending JSON.
  • Serialize your ViewModel object with JSON.stringify() before passing it as data.

Wrong Approach:

$.ajax({
    url: "/User/SubmitData",
    type: "POST",
    data: viewModel, // No serialization, wrong content type
    success: function(res) { ... }
});

Correct Approach:

$.ajax({
    url: "/User/SubmitData",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(viewModel),
    success: function(res) { ... }
});

For GET requests (not recommended for complex objects), you'd pass data as key-value pairs instead of JSON, but POST is the standard for sending ViewModels.

3. ViewModel Accessibility & Constructor Issues

Make sure your ViewModel class is public, and that it has a public parameterless constructor. If you've defined a custom constructor with parameters, you need to explicitly add a parameterless one—otherwise the model binder can't instantiate the object.

Example of a valid ViewModel:

public class UserViewModel
{
    // Required for model binding
    public UserViewModel() { }

    // Custom constructor (optional)
    public UserViewModel(string name)
    {
        FullName = name;
    }

    public string FullName { get; set; }
    public int UserAge { get; set; }
}
4. Errors in Fetching Frontend Values

You mentioned the jQuery variable itself is null—first debug this directly in your browser's console:

  • Run console.log(viewModel) after constructing the object to check if any properties are missing or incorrectly fetched.
  • Verify your DOM selectors are correct: e.g., $("#fullNameInput") actually targets an existing element with that ID.
  • For special controls like checkboxes or dropdowns, use the right methods to get values:
    • Checkboxes: $("#agreeCheckbox").is(":checked")
    • Dropdowns: $("#roleSelect").val()
5. Controller Action Parameter Configuration

In ASP.NET Core, you need to add the [FromBody] attribute to your ViewModel parameter for POST requests using JSON payloads. Without it, the model binder won't look for data in the request body.

Example of a correct action:

[HttpPost]
public IActionResult SubmitData([FromBody] UserViewModel model)
{
    if (model == null)
    {
        return BadRequest("Failed to bind ViewModel");
    }
    // Your business logic here
    return Ok();
}

Note: ASP.NET MVC (non-Core) doesn't require [FromBody] for JSON POSTs, as long as the content type is set correctly.

6. Hidden Model Validation Failures

If your ViewModel has data annotations like [Required] or [Range], invalid values from the frontend can cause the model binder to return a null object (or an object with missing values). Always check ModelState.IsValid in your controller to catch this:

[HttpPost]
public IActionResult SubmitData([FromBody] UserViewModel model)
{
    if (!ModelState.IsValid)
    {
        // Log or return validation errors
        var errors = ModelState.Values.SelectMany(v => v.Errors);
        return BadRequest(errors);
    }
    // Proceed with logic
    return Ok();
}

If you've checked all these and still have issues, sharing your actual ViewModel code, jQuery snippet, and controller action would help pinpoint the exact problem.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:29:59