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

如何在macOS上用C#和ASP.NET Core实现带数字验证的Web应用

实现步骤(Mac环境)

1. 创建ASP.NET Core MVC项目

打开终端,执行以下命令:

dotnet new mvc -n NumberInputApp
cd NumberInputApp

2. 添加视图模型(ViewModel)

在Models目录下新建NumberInputViewModel.cs,用来封装输入内容、结果和错误信息:

namespace NumberInputApp.Models;

public class NumberInputViewModel
{
    public string? InputText { get; set; }
    public string? ResultMessage { get; set; }
    public string? ErrorMessage { get; set; }
}

3. 修改Home控制器

更新Controllers/HomeController.cs,添加处理表单提交的逻辑:

using Microsoft.AspNetCore.Mvc;
using NumberInputApp.Models;

namespace NumberInputApp.Controllers;

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View(new NumberInputViewModel());
    }

    [HttpPost]
    public IActionResult Index(NumberInputViewModel model)
    {
        if (int.TryParse(model.InputText, out int number))
        {
            model.ResultMessage = $"You've entered {number}";
            model.ErrorMessage = null;
        }
        else
        {
            model.ErrorMessage = "It is not a number!!!";
            model.ResultMessage = null;
        }

        return View(model);
    }
}

这里用int.TryParse替代try-catch,更符合Web开发的简洁处理逻辑,效果和原控制台程序的异常捕获一致。

4. 更新Index视图

替换Views/Home/Index.cshtml的内容,添加输入表单和结果/错误展示区域:

@model NumberInputApp.Models.NumberInputViewModel

@{
    ViewData["Title"] = "Number Input";
}

<h1>Enter a number:</h1>

<form method="post">
    <div class="form-group">
        <input type="text" asp-for="InputText" class="form-control" placeholder="Type a number here..." />
    </div>
    <button type="submit" class="btn btn-primary mt-2">Submit</button>
</form>

@if (!string.IsNullOrEmpty(Model.ResultMessage))
{
    <div class="alert alert-success mt-3">@Model.ResultMessage</div>
}

@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
    <div class="alert alert-danger mt-3">@Model.ErrorMessage</div>
}

5. 运行项目

在终端执行:

dotnet run

启动后,在浏览器访问http://localhost:5000即可测试功能:输入数字提交会显示成功信息,输入非数字会显示错误提示。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:55:20