我有一个应用程序,主要是使用ET6DBFirst+控制器/视图脚手架生成的。我的概念混淆了从Razor与我的控制器发帖。基本上,我的数据并没有通过DOM。
这是我的控制器:(不要介意验证设置,这不是一个面向公众的应用程序)
namespace RegTeg.Controllers
{
public class HomeController : Controller
{
private VRIIntegrationEntities db = new VRIIntegrationEntities();
public ActionResult Index()
{
return View(db.ApplicationNames.ToList());
}
[HttpPost]
// [ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Index([Bind(Include = "appName")] RegTeg.Models.ApplicationName newAppName)
{
if (ModelState.IsValid)
{
db.ApplicationNames.Add(newAppName);
db.SaveChanges(); //fails here due to a null column
return RedirectToAction("Index");
}
return View(newAppName);
}
}
}因此,我有了我的索引,在这个索引中,我向视图传递了一个列表,这样我就可以在访问页面时将数据库中的数据显示给用户。在这个页面上也有一个帖子,他们可以添加一些东西到DB。我将它传递给我的模型的一个实例,然后插入到表中。所以这一切都很好(所以我觉得)。
现在我的看法是:
@model IEnumerable<RegTeg.Models.ApplicationName>
<div>
<select class="applicationSelect">
@foreach (var item in Model)
{
<option>
@Html.DisplayFor(modelItem => item.appName)
</option>
}
</select>
</div>
@using (Html.BeginForm())
{
RegTeg.Models.ApplicationName appModel = new RegTeg.Models.ApplicationName();
<div class="form-horizontal">
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<h3>Add New Application for Testing:</h3>
<div class="form-group">
@Html.LabelFor(model => appModel.appName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => appModel.appName)
@Html.ValidationMessageFor(model => appModel.appName)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}我传递我的强类型模型。把数据放进我的前轮..。好了,完成了,现在我想给我的服务器发个帖子,然后把新的数据添加到我的数据库中。我创建了一个新的模型实例,从我的输入中提取数据,并将其提交。但问题是,数据是null。我有一种预感,这与我的@model声明有关。例如,post需要一个@model RegTeg.Models.ApplicationName,但是我认为以后在我的视图中声明新实例时没有必要吗?我希望我说得够清楚。提前谢谢。
发布于 2014-10-30 16:59:11
问题1:
我猜您仍然希望显示所有的应用程序,所以我建议您在最初所做的工作之后对您的帖子进行建模:
[HttpPost]
// [ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Index([Bind(Include = "appName")] RegTeg.Models.ApplicationName newAppName)
{
if (ModelState.IsValid)
{
db.ApplicationNames.Add(newAppName);
db.SaveChanges(); //fails here due to a null column
return RedirectToAction("Index");
}
//continue to return a list as your view is expecting
//if you REALLY want only the item that you just created, then construct a list,
//add that to it, and return that instead of the full list
return View(db.ApplicationNames.ToList());
}问题2:
看看你的HTML。您需要做的是确保textbox上的NAME属性与ActionMethod的变量名相同。例如,如果文本框如下所示:
<input type="text" name="appName" id="appName" />然后,我建议去掉您所拥有的绑定内容,只需这样做:
[HttpPost]
// [ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Index(RegTeg.Models.ApplicationName appName)
{
... existing code here ...
}https://stackoverflow.com/questions/26658078
复制相似问题