除了我的评论之外,还有一个更复杂的答案。
大致包含以下几项:
- 视图:CreateItem、NewItemHandler
- 控制器:ItemHandler
- Javascript:site.js 和 jQuery
CreateItem 视图是用户输入项目值的对话框。在我的例子中,一个简单的表单包含两个 input 字段和强制性的 submit 按钮。
@{
ViewBag.Title = "CreateItem";
}
<h2>CreateItem</h2>
<form id="newItemForm">
Item name: <input id="itemname" type="text" name="fname"><br>
Item weight: <input id="itemweight" type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
点击submit 时,JavaScript 应该停止重定向,这是通过在$("newItemForm").submit(...) 中返回false 来完成的。此外,我们不需要告诉服务器它需要创建我们的项目,所以我们必须创建自己的提交请求,我用jQuery.post() 完成了:
$('#newItemForm').submit(function () {
sendPostAndShowResult();
return false;
});
function sendPostAndShowResult() {
var name = $("#itemname").text();
var weight = $("#itemweight").text();
$.post("/Item/NewItemHandler",
{ "name": name, "weight": weight }
).done(function (data) {
alert("The ID of your new item is: " + $.trim(data)); //replace with toast
})
.fail(function () {
alert("Error while processing the request!");
});
}
只是一个提示:我这里没有用 toast,因为我没用过,但我想应该不会太难适应。
拼图的最后一块是NewItemHandler,它创建项目、计算 ID 并返回值:
视图很简单。由于我们不需要 Layout,因此已将其设置为 ""。
@{
Layout = "";
}
@Html.Raw(Session["ItemID"])
如您所见,我们只需要将“ItemID”获取到我们的 Session 对象中,这是由 Controller 完成的。
[HttpPost]
public ActionResult NewItemHandler(string name, string weight)
{
int id = GenerateNewItem(name, weight);
Session["ItemID"] = id;
return View();
}
编辑:我尝试使这种方法适应您的解决方案:
您需要在控制器中删除 return RedirectToAction() 和 return View();。然后返回 (Save.cshtml) 一个响应,其 ID 在一个空文件 (Layout = "") 中。
我猜你的Save.cshtml 是空的,所以用
替换它
@{
Layout = "";
}
@Html.Raw(Session["ItemID"])
在您的控制器中,Save 方法应该看起来像这样。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(BidstonHwrc bidstonhwrc)
{
_context.BidstonHwrc.Add(bidstonhwrc);
try
{
_context.SaveChanges(); //either all changes are made or none at all
}
catch (Exception e)
{
Console.WriteLine(e);
}
int id = bidstonhwrc.Id;
Session["ItemID"] = id;
return View();
}
在您的 MCN Form 中,您需要通过 Razor 为您的 <form> 标签提供一个 ID:
@using (Html.BeginForm("Save", "BidstonHwrc",FormMethod.Post, new { id = "SaveBidstonHwrc" }))
javascript 代码应如下所示,只需调整 ID:
$('#SaveBidstonHwrc').submit(function () {
sendPostAndShowResult();
return false;
});
function sendPostAndShowResult() {
//foreach Model/ViewModel Property one line e.g.
var Id = $("Id").text();
var McnNumber = $("McnNumber").text();
$.post("/BidstonHwrc/Save",
{ "Id": Id, "McnNumber": McnNumber }
).done(function (data) {
alert("The ID of your new item is: " + $.trim(data)); //replace with toast
$(location).attr('href', '/Home/Index') //Redirect to Home
})
.fail(function () {
alert("Error while processing the request!");
});
}
我上传了一个项目,该项目应该能代表您的解决方案。
你可以在这里下载(28MB):Project download