【问题标题】:Form binding giving null properties提供空属性的表单绑定
【发布时间】:2017-09-30 17:58:37
【问题描述】:

我已经尝试了几种方法来处理尝试解决问题,例如

默认Binder问题:https://stackoverflow.com/a/37601937/4444304

而且他们都没有工作...... 这显然也不是嵌套的。其中大部分是嵌套问题引起的……

Form.Request 正在获取提交的参数。只是模型似乎没有分配:s

更奇怪的是,该字段被标记为必填项。但是模型状态也返回为有效。

我真的看不出我能找到更多或做更多...谢谢。

我的模型如下所示
EmailSubmitModel.cs

using System.ComponentModel.DataAnnotations;

namespace myapp.Models.Home
{
    public class EmailSubmitModel
    {
        [Required(ErrorMessage = "Please enter your name")]
        public string FriendName;
    }
}

HomeController.cs

using myapp.Models.Home;

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Submit(EmailSubmitModel emailSubmitModel)
{
    if (ModelState.IsValid)
    {
        return Json(emailSubmitModel);
    }
    return View(emailSubmitModel);
}

index.cshtml

@using myapp.Models.Home
@model EmailSubmitModel
<form asp-controller="Home" asp-action="Submit" method="post">
    <div asp-validation-summary="All"></div>
    <label asp-for="FriendName">@Localizer["Friend's Name"]</label>
    <input asp-for="FriendName" type="text" />
    <span asp-validation-for="FriendName"></span>
    <input type="submit" class="btn btn-warning">@Localizer["Send the email"]</button>
</form>

【问题讨论】:

  • 很好的尝试...但asp-for 实际上会生成name 列。根据您的建议,我也尝试过手动分配它。但没有运气:(
  • 试试这个:将{ get; set; }添加到FriendName属性的模型中。
  • 模型绑定器不绑定字段,只绑定属性 - 将其更改为public string FriendName { get; set; }
  • 感谢大家的cmets。我认为我对属性和字段有错误的概念。应该多学习 C# 哈哈

标签: c# asp.net-mvc asp.net-core asp.net-core-mvc asp.net-core-2.0


【解决方案1】:

FriendName 应声明为property。目前是一个字段:

public string FriendName { get; set; }

【讨论】:

  • 我已经接受了答案。 { 得到;放; } 是要走的路 =[]='' 但是 asp-for 确实会生成 name 字段 FYR
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-08
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
  • 2017-01-18
相关资源
最近更新 更多