【问题标题】:SelectList is causing me to get null valuesSelectList 导致我得到空值
【发布时间】:2021-03-31 14:39:22
【问题描述】:

在我的 ASP.NET Core 项目中,由于 selectList,我的模型得到了空值。我的所有属性都从我的视图中发布为空,除了我从下拉列表中选择的选择,我使用 selectList 选择。我正在尝试使用标签助手 asp-items 进行下拉选择。我想设置 HTML 表单中的所有数据并保存在名为“Student”的同一模型中

我的模型;

public class Student
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string branch { get; set; }

}

我的控制器和我发送给我的 selectList 的线路;

public async Task<IActionResult> Signup(Student student) //properties of student come null except branch.
{
    ViewBag.branches = new List<string>() { "Web Programlama", "Mobil Programlama", "Veri Bilimi", "Yapay Zeka/Makine Öğrenmesi", "Genel Tavsiye" };
    return View();      
}
        

还有我称为 selectedList 的 HTML 行;

<select asp-for="student.branch" class="form-control" id="alan" asp-items="@(new SelectList(ViewBag.branches))"> //here is where ı stuck :(
<option disabled selected title="Alanınızı seçiniz">Alanınızı seçiniz</option>
</select>

【问题讨论】:

  • 如何在 HTML 顶部初始化 @model
  • 我有 TotalModel 类,其中包括我所有的模型类; public class TotalModel { public User user { get; set; } public Mentor mentor { get; set; } public Student student { get; set; } public Branch branch { get; set; } } 和 HTML 的顶部; @model MENTOR.Models.TotalModel
  • @AlperenÖz asp-for="student.branch" 这可能不会直接映射到学生模型。更新您的操作方法以接受 TotalModel 并查看您是否有值。为了自动映射,html 元素的name 应该与模型属性匹配。如果您检查当前的select,它的名称将是student_branch,它不会直接映射到branch。结构需要匹配。
  • @Pirate Yesss 成功了!你拯救了我的一天 :)) 我所做的只是将 student.branch 重命名为 branch。但我猜我的逻辑仍然不正确。 :// 为什么select标签中可以通过student.branch成功获取其他属性的时候不一样?
  • @Pirate 和我的控制器方法仍然接受 Student 类作为操作参数

标签: html .net asp.net-mvc asp.net-core tag-helpers


【解决方案1】:

首先,您需要在&lt;select&gt;&lt;/select&gt; 中添加name="branch"。然后,您需要在add value to option 中添加。

代码

<select asp-for="student.branch" class="form-control" id="alan" asp-items="@(new SelectList(ViewBag.branches))"> //here is where ı stuck :(
<option disabled selected title="Alanınızı seçiniz">Alanınızı seçiniz</option>
</select>

在 html 中会是这样,选项没有值:

这是一个工作演示:

查看:

<form method="post">
        
        <select asp-for="student.branch" name="branch" class="form-control" id="alan">
            //here is where ı stuck :(
            <option disabled selected title="Alanınızı seçiniz">Alanınızı seçiniz</option>
            @foreach (var branch in @ViewBag.branches)
            {
                <option value=@branch>@branch</option>
            }
        </select>
        <button type="submit">submit</button>
    </form>

结果:

【讨论】:

  • 非常感谢!!我也会用这个:)
  • 我只有=name = "branch",它在我的选择标签中工作。 @Yiyi优
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
相关资源
最近更新 更多