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

解决Microsoft.AspNetCore.Mvc中RazorPage.Model.get返回null错误

解决RazorPage.Model.get返回null的问题

问题根源

  1. 首次加载页面时Model未初始化:Index方法返回View时没有传入CaseConverterModel实例,导致页面渲染时@Model为null,访问@Model.OutPutText触发空引用异常。
  2. 表单控件未正确绑定Model:textarea没有设置name属性,无法将用户输入传递给后端;同时直接使用独立参数inputText不符合Model绑定的最佳实践。

修复步骤

1. 修改Controller的Index方法,初始化Model

public IActionResult Index()
{
    // 传入空的Model实例,确保页面首次加载时Model不为null
    return View(new CaseConverterModel());
}

2. 优化Controller的Post方法,使用Model接收参数

[HttpPost]
public IActionResult ConvertToTitleCase(CaseConverterModel model)
{
    // 这里可以替换为实际的标题大小写转换逻辑
    // 示例:使用系统方法实现标题转换
    // model.OutPutText = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(model.InputText?.ToLower() ?? string.Empty);
    
    // 保留你的测试输出
    model.OutPutText = "this is test";
    return View(nameof(Index), model);
}

3. 修改View中的表单控件,实现正确绑定

将原textarea替换为使用asp-for标签帮助器,自动生成绑定所需的name属性,并支持回显输入内容:

<form asp-action="ConvertToTitleCase">
    <!-- 使用asp-for绑定到Model的InputText属性 -->
    <textarea asp-for="InputText" class="form-control" style="width:100%"></textarea>
    <br />
    <input type="submit" value="Convert" class="btn btn-primary" />

    <hr />
    <!-- 添加空值判断,避免极端情况报错 -->
    <p>@(Model.OutPutText ?? string.Empty)</p>
</form>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:40:27