我刚刚开始使用MVC,而且我正处于学习阶段。我目前仍然遇到这个问题。在我的洗礼中,我得到了这两张桌子。
TopicTable -TopId -TopName
ContentTable -ContId -TopId -content
我希望我能够在Topic Detailes视图中创建新内容。
在detailes.cshtml文件中,我添加了:
@Html.ActionLink("Create New Content", "Create", "Content", new { ID = Model.TopicId}, null)` which will display in URL: localhost/Content/Create/1
在我的ContentController中,我得到了这个,并且在提交" 一个或多个实体的验证失败时收到此错误。请参阅' EntityValidationErrors'财产了解更多详情。"
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int Id)
{
ContentModel content = new ContentModel();
if (ModelState.IsValid)
{
content.TopId = Id;
db.ContentModel.Add(content);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(content)
}
观点:
@model WebApplication2.Models.ContentModel
@{
ViewBag.Title = "Create";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>JobOfferModel</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Content)
@Html.ValidationMessageFor(model => model.Content)
</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>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
型号:
public class Topic
{
[Display(Name = "Id")]
public virtual int TopicId{ get; set; }
[Display(Name = "Name")]
public virtual string TopicName{ get; set; }
}
public class Content
{
[Display(Name = "Id")]
[Display(Name = "Id")]
public virtual int ContentId{ get; set; }
[Display(Name = "TopicId")]
public virtual string TopicId{ get; set; }
[AllowHtml]
[Display(Name = "Innihald")]
public virtual string Content { get; set; }
}
因此,当我创建新内容时,topId值将自动添加到内容表中。
希望得到一些帮助,格拉西亚斯
答案 0 :(得分:0)
@Html.ActionLink()
是对GET方法的调用。您需要GET才能返回呈现表单的视图,以及POST方法来接收和保存表单数据
public ActionResult Create(int ID)
{
Content model = new Content();
model.TopicId = ID; // note TopicId should be int, not string
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Content model)
{
if(!ModelState.IsValid)
{
return View(model);
}
// save your model and redirect.
}
查看(省略了div等)
@model WebApplication2.Models.Content
....
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(m => m.TopicId) // for postback
@Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" })
@Html.TextBoxFor(model => model.Content)
@Html.ValidationMessageFor(model => model.Content)
<input type="submit" value="Create" class="btn btn-default" />
}
....