我显然在这里错过了什么,我无法为我的一生想出什么。我可以很好地填充模型并将其发送到视图,但是在post中,大多数数据都是空的或默认的。
我强制使用/ test /createa1=5&a2=6&shell=7来输入Create,这对于初始化测试实体来说很好。POST具有名称和CatId,但其他属性为null。
任何帮助都将不胜感激。
模型
namespace MyApp.Models
{
public partial class TestEntity
{
[DisplayName("Entity Id")]
[Required]
public int? EntityId { get; set; }
[Required]
[DisplayName("Entity Name")]
public string EntityName { get; set; }
[DisplayName("Category Id")]
[Required]
public int? CatId { get; set; }
[DisplayName("Attribute 1")]
public int? Attribute1 { get; set; }
[DisplayName("Attribute 2")]
public int? Attribute2 { get; set; }
}
}视图
@model MyApp.Models.TestEntity
<h2>Test</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<p>
@Html.LabelFor(model => model.EntityName)
@Html.TextBoxFor(model => model.EntityName)
</p>
<p>
@Html.LabelFor(model => model.CatId)
@Html.TextBoxFor(model => model.CatId)
</p>
<p>
@Html.LabelFor(model => model.Attribute1)
@Html.DisplayFor(model => model.Attribute1)
</p>
<p>
@Html.LabelFor(model => model.Attribute2)
@Html.DisplayFor(model => model.Attribute2)
</p>
<input type="submit" value="Done" />}
控制器
using System.Web.Mvc;
using MyApp.Models;
namespace MyApp.Controllers
{
public class TestController : Controller
{
//
// GET: /Test/Create
public ActionResult Create(int? a1, int? a2, int? shell)
{
using (var db = new MyDbContext())
{
ShellEntity temp =
db.ShellEntities.Where(se => se.ShellId == shell).FirstOrDefault();
TestEntity model = new TestEntity();
model.CatId = temp.category; //get the category id from the shell
model.Attribute1 = a1;
model.Attribute2 = a2;
return View(model);
}
}
//
// POST: /Test/Create
[HttpPost]
public ActionResult Create(TestEntity model)
{
try
{
//at this point model.Attribute1 and Attribute2 are both null
if (!model.Attribute1.HasValue)
{
//WTF???
}
return View(model);
}
catch
{
return View(model);
}
}
}
}发布于 2014-05-29 20:58:41
你需要用
@Html.HiddenFor(model => model.Attribute1)将值传递给控制器而不是DisplayFor()
发布于 2014-05-29 21:08:34
更改此代码
<p>
@Html.LabelFor(model => model.Attribute1)
@Html.DisplayFor(model => model.Attribute1)
</p>
<p>
@Html.LabelFor(model => model.Attribute2)
@Html.DisplayFor(model => model.Attribute2)
</p>对此:
<p>
@Html.LabelFor(model => model.Attribute1)
@Html.HiddenFor(model => model.Attribute1)
@Html.DisplayFor(model => model.Attribute1)
</p>
<p>
@Html.LabelFor(model => model.Attribute2)
@Html.HiddenFor(model => model.Attribute2)
@Html.DisplayFor(model => model.Attribute2)
</p>而且它应该能正常工作。
基本上,它添加了<input name="Attribute1" value="your_value"/>,所以在单击submit按钮后,它将被包含到POST中。
https://stackoverflow.com/questions/23942538
复制相似问题