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

Razor Page表单绑定后无法获取用户提交内容该如何解决?

问题根因
  • 类属性的set访问器为private:ASP.NET Core模型绑定系统在接收表单提交数据时,需要对绑定目标的属性进行写入操作,private级别的set访问器会阻止写入,导致所有属性保留默认值(int为0、字符串为null、bool为false)
  • 布尔类型字段绑定不匹配:表单中isEmergency下拉选项的值为Yes/No,无法自动转换为C#的bool类型,导致绑定失败
  • 可选展示问题:Byline对应的label标签asp-for属性错误绑定到了title字段,仅影响展示不影响绑定逻辑
  • 可选遗漏问题:如果PageModel中的ArticleNews属性未添加[BindProperty]特性,Razor Page默认不会对POST请求的页面属性进行自动绑定

修复方案

1. 修改属性访问权限

将Article基类和NewsArticle子类中需要绑定的属性set访问器改为public:

public abstract class Article
{
    public Article()
    { }

    public Article(int id, string title, string text)
    {
        this.id = id;
        this.title = title;
        this.text = text;
    }

    [Required]
    public int id { get; set; }
   
    public string title { get; set; }
    
    public string text { get; set; }

    public bool HasID(int id)
    {
        return id == this.id;
    }

    public override string ToString()
    {
        return "Id: " + id + " Title: " + title + " Text: " + text;
    }
}
public class NewsArticle : Article
{
    public NewsArticle()
        {}

    public NewsArticle(int id, string title, string text, bool isEmergency, string byLine, string source)
        : base(id, title, text)
    {
        this.isEmergency = isEmergency;
        this.byLine = byLine;
        this.source = source;
    }

   
    public bool isEmergency { get; set; }
  
    public string byLine { get; set; }
    
    public string source { get; set; }

    public override string ToString()
    {
        return base.ToString() + " Made by: " + byLine + " Used sources: " + source;
    }
}

2. 修正布尔字段下拉选项

将isEmergency下拉框的value值改为和bool类型匹配的true/false:

<select asp-for="ArticleNews.isEmergency">
    <option value=""></option>
    <option value="true">Yes</option>
    <option value="false">No</option>
</select>

3. 修正错误的label绑定

修改Byline对应的label标签:

<label asp-for="ArticleNews.byLine">Byline*</label>

4. 为PageModel属性添加绑定特性

确认你的MakeNewsArticleModel中ArticleNews属性添加了[BindProperty]特性:

public class MakeNewsArticleModel : PageModel
{
    [BindProperty]
    public NewsArticle ArticleNews { get; set; }

    public IActionResult OnPost()
    {
        if (ModelState.IsValid)
        {
            // 替换为你的输出逻辑即可正常读取提交数据
            ViewData["Message"] = $"The article id is: {ArticleNews.id} The title is: {ArticleNews.title} It is written by: {ArticleNews.byLine} The written text is: {ArticleNews.text} It was an {ArticleNews.isEmergency} news article And the used source was: {ArticleNews.source}";
        }
        return Page();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:18:03