Null value on POST in ASP.NET MVC
我正在学习 ASP.NET MVC,但遇到以下问题。
视图”SelectProdotti”是
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
@model Models.SelectProdottiModel
@{ @ViewBag.Title @using (Html.BeginForm(“ProdottiToListino”,“Listino”, FormMethod.Post))
@Html.HiddenFor(m => m.id)
<input type=“submit” value=“Salva” /> |
加载视图的动作
1
2 3 4 5 6 7 8 9 |
public ActionResult SelectProdotti(int id)
{
SelectProdottiModel model = new SelectProdottiModel(); return View(model); |
型号
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System;
using System.Collections.Generic; using System.Linq; using System.Web; namespace Models public int id; public SelectProdottiModel() |
控制器中的发布动作
1
2 3 4 5 6 |
[HttpPost]
public ActionResult ProdottiToListino(SelectProdottiModel model) { return RedirectToAction(“SelectProdotti”,“Listino”, new {id = model.id }); |
我写这段代码只是为了学习,没用。问题是model.id始终为0,即视图不发布值,错误在哪里?
- public int id 是一个字段。默认的模型绑定器甚至不会尝试绑定它。尝试使用属性:public int id { get; set; }
当前 Id 是您的类的一个字段,没有 GETTER/SETTER 属性/方法。
字段通常用于在类内部存储数据(这些将具有默认私有可见性)。通常,字段的值将通过另一个公共属性或方法设置/读取。使用 C# 属性,这更容易,如果你想让一个字段可读可写,你可以创建一个像
这样的公共属性
1
|
public int Age {set;get;}
|
当您从表单发布数据时,DefaultModelBinder(将表单数据映射到类对象的类)将尝试创建 SelectProddottiModel 类的对象并尝试设置匹配的公共属性的值与发布的表单数据中的表单项的名称。如果您不使用 set 访问器将您的字段设置为公共属性,则模型绑定器无法设置该值。
将您的字段 Id 更改为具有 set 和 get 的属性,以便 ModelBinder 可以从发布的表单数据中设置值。
1
2 3 4 |
public class SelectProdottiModel
{ public int id {set;get;} } |
此外,C# 通常使用 PascalCasing。所以我建议你将 Id 属性更改为 Id
- 不正确 – C# 属性通常是 Pascal 大小写,而不是 Camel 大小写。 C# 字段通常是 ??Camel 大小写。
- @NightOwl888 哎呀!我用错了。感谢您的关注。
来源:https://www.codenong.com/34383936/