ASP.NET MVC创建功能无法在页面上工作
本文关键字:工作 NET MVC 创建 功能 ASP | 更新日期: 2023-09-27 18:02:43
我已经创建了一个使用实体框架检索/在数据库中显示信息的页面,我还在同一页面上的部分视图中创建了功能,但它不保存/插入数据。
这是我的Home View:
@model IEnumerable<TerminalHost.Models.buildingInfo>
@{
ViewBag.Title = "Home Page";
}
<h3>We suggest the following:</h3>
<ol class="round">
<li class="one">
<h5>Please begin creating your network structure:</h5> <button id="modal-opener">Add a new building</button>
</li>
<li class="two">
</li>
</ol>
<div class="Container">
<div class="Box1">
@foreach (var item in Model)
{<div>
<h4 class="Heading">@item.buildingName</h4>
<h4 class="Heading">@item.buildingNumber</h4>
<p>@item.buildingDesc1</p>
<p>@item.buildingDesc2</p>
<p>@item.buildingDesc3</p>
</div>
}
</div>
</div>
<div id="Modal" title="Building Details">
@Html.Partial("buildForm", new TerminalHost.Models.buildingInfo())
</div>
这是我的局部视图:
@model TerminalHost.Models.buildingInfo
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>buildingInfo</legend>
<div class="editor-label">
@Html.LabelFor(model => model.buildingNumber)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.buildingNumber)
@Html.ValidationMessageFor(model => model.buildingNumber)
</div>
....
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
这是我的控制器:
public class HomeController : Controller
{
thDB _db = new thDB();
public ActionResult building()
{
var buildingModel = _db.buildings.ToList();//you have to remove the FirstOrDefault() extension method
return View(buildingModel);
}
public ActionResult buildForm()
{
return PartialView();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult buildForm(buildingInfo buildinginfo)
{
if (ModelState.IsValid)
{
_db.buildings.Add(buildinginfo);
_db.SaveChanges();
return RedirectToAction("Index");
}
return PartialView(buildinginfo);
}
protected override void Dispose(bool disposing)
{
if(_db != null)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
我已经尝试复制相同的代码作为脚手架模板,是创建做CRUD功能,但他们被分开到不同的视图,而我希望他们都在一个页面上。
你需要的是告诉你的局部视图要调用的Action。你能改一下这一行吗?
@using (Html.BeginForm())
@using (Html.BeginForm("builForm","Home"))
And in your Action:
HttpPost]
[ValidateAntiForgeryToken]
public ActionResult buildForm(buildingInfo buildinginfo)
{
if (ModelState.IsValid)
{
_db.buildings.Add(buildinginfo);
_db.SaveChanges();
return RedirectToAction("Index");
}
return PartialView(buildinginfo);//instead of return this you can redirect to Index so you can see the update. Just a suggestion
}