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

ASP.NET Core MVC视图无法显示新模型值问题求助

ASP.NET Core MVC + TypeScript 视图不显示返回模型数据的问题

问题概述

开发ASP.NET Core MVC结合TypeScript的Web应用时,代码无报错,但点击按钮提交数据后,Display Action返回携带模型的Index视图,页面却始终显示“Nothing to show”。调试确认Action中的Model.Age大于0,但浏览器不渲染模型内容。

相关代码

Person.ts

export interface IPerson {
    FirstName: string;
    LastName: string;
    Email: string;
    DOB: Date;
    Age: number;
}

app.ts

import { IPerson } from '../typeScripts/Person';

window.onload = (event) => {
    //alert('page is fully loaded');
};

document.getElementById("btn_DOB").onclick = (event) => {
    let DOB = document.getElementById("txt_dob") as HTMLInputElement;
    if (DOB.value) {
        let diff = Math.abs(new Date(DOB.value).getTime() - new Date().getTime());
        let diffDays = Math.ceil(diff / (1000 * 3600 * 24));

        let _person = {} as IPerson;
        _person.FirstName = (document.getElementById('fname') as HTMLInputElement).value;
        _person.LastName = (document.getElementById('lname') as HTMLInputElement).value;
        _person.Email = (document.getElementById('txt_email') as HTMLInputElement).value;
        _person.DOB = new Date((document.getElementById('txt_dob') as HTMLInputElement).value);
        _person.Age = diffDays;

        fetch('/Home/Display/',
            {
                method: 'POST',
                headers: {
                    'Content-type': 'application/json',
                },
                body: JSON.stringify(_person)
            }
        )
            .then((Response) => {
                if (Response.ok) {
                    console.log(Response);
                }
            })
            .catch((Error) =>
            { console.log(Error) });
    }
    else {
        alert('First Select a Date')
    }
};

ASP.NET Core MVC Action方法

[HttpPost]
public IActionResult Display([FromBody] Person _person)
{
    return View("Index", _person);
}

Razor视图

@model MVC_TS.Models.Person

@{
    ViewData["Title"] = "Home Page";
}

<form>
    <div class="container container-fluid">
        <div class="row g-3">
            <div class="col">
                <input type="text" class="form-control" placeholder="First name" aria-label="First name" id="fname">
            </div>
            <div class="col">
                <input type="text" class="form-control" placeholder="Last name" aria-label="Last name" id="lname">
            </div>
        </div>
        <div class="p-2"></div>
        <div class="row g-3">
            <div class="col">
                <input type="datetime-local" class="form-control" placeholder="Date Of Birth" aria-label="DOB" id="txt_dob">
            </div>
            <div class="col">
                <input type="email" class="form-control" placeholder="Email ID" aria-label="Email" id="txt_email">
            </div>
        </div>
        <div class="p-2"></div>
        <div class="row g-3">
            <input type="button" class="btn btn-info" value="Click" id="btn_DOB" />
        </div>
        @if (Model.Age > 0)
        {
        lastname:  <input asp-for="LastName" />
            <p>@Model.FirstName;</p>
            <p>@Model.LastName;</p>
            <p>@Model.DOB;</p>
            <p>@Model.Age;</p>
        }
        else
        {
            <p>Nothing to show</p>
        }
    </div>
</form>

<script>var exports = {};</script>
<script type="module" src="~/js/app.js"></script>

问题原因

核心问题在于你使用fetch发起了AJAX异步请求,而非传统的表单提交:

  • AJAX请求的响应会被fetch的回调函数捕获,但浏览器不会自动刷新页面或替换当前页面内容。
  • 你的Display Action返回了完整的Index视图HTML,但这份HTML只是作为AJAX响应数据存在,并没有被注入到当前页面中。页面始终保持初始加载时的状态(初始Model.Age为0),因此显示“Nothing to show”。

解决方案

提供两种可行的解决思路:

思路1:改用传统表单提交(无需AJAX)

如果不需要异步更新页面,直接用表单提交即可:

  1. 修改表单属性,指定提交地址和方法:
    <form asp-action="Display" method="post">
    
  2. 将按钮改为submit类型:
    <input type="submit" class="btn btn-info" value="Click" id="btn_DOB" />
    
  3. 移除Action的[FromBody]特性(表单提交使用form-data绑定,而非JSON):
    [HttpPost]
    public IActionResult Display(Person _person)
    {
        return View("Index", _person);
    }
    
  4. 可删除TypeScript中fetch相关代码,或保留日期计算逻辑,在表单提交前通过隐藏域存储Age值。

思路2:继续使用AJAX,手动更新页面

若需要异步更新,需在fetch回调中处理响应的HTML并替换页面内容:

  1. 修改app.ts中的fetch回调:
    fetch('/Home/Display/',
        {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
            },
            body: JSON.stringify(_person)
        }
    )
    .then(response => response.text()) // 获取响应的HTML文本
    .then(html => {
        // 替换整个页面内容
        document.documentElement.innerHTML = html;
        // 或只替换特定区域:给结果部分添加id="result-container"后,替换其innerHTML
        // document.getElementById('result-container').innerHTML = html;
    })
    .catch(error => console.log(error));
    
  2. 注意:替换页面后原事件绑定会失效,需重新绑定事件或使用事件委托(将事件绑定到父元素,通过事件冒泡触发)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:05:21