我正在开发小型 mvc 应用程序,有一点我需要来自 Controller 方法的值, 我的计划是将该值存储在 ViewBag 中并将其获取到 View 上,所以我接下来做了:
ViewBag.SuccessBody = "This is a test";
在我的 Razor View 上我接下来要做的是:
<input id="customInput" type="hidden" value='@(ViewBag.SuccessBody)' />
//出于测试目的,我也尝试了下面的示例..
<input id="customInputAgain" type="hidden" class="form-control" value="@(ViewBag.SuccessBody)">
当 View 加载时,我试图获取一个值,所以我写了这个:
<script>
$(document).ready(function () {
var customVal = $("#customInput").val();
var customValAgain = $("#customInputAgain").val();
alert(customVal);
alert(customValAgain);
});
</script>
我什至尝试添加
alert(customVal.value);
alert(customValAgain.value);
但它也不起作用,所以看起来我没有从我的 Controller /ViewBag 中检索值,这就是原因 为什么警报总是显示空白区域 - 什么都没有。
编辑:
我在我的文章的编辑上设置此 ViewBag 值,实际上是在 [HttpPost] EDIT
上设置,因此当用户单击“保存更改”时 [HttpPost] EDIT
方法是调用并且当数据可能插入到数据库中时,我设置 ViewBag 值并将用户重定向到相同的 [HttpGet] Edit 方法。这是它的样子:
[HttpPost]
public ActionResult Edit(ArticleEditViewModel model)
{
if (ModelState.IsValid)
{
//Rest of the code
ViewBag.SuccessBody = "This is a test";
return RedirectToAction("Edit/" + product.Id, "Article");
}
else
{
return View("NotFound");
}
return View(model);
}
正如你所见,我定义了 ViewBag,但我无法获取应存储在输入控件中的 View 的值。
也许问题是因为我在 HttpPost Action 方法中定义了 ViewBag,而不是在 HttpGet 我从哪里“打开 View ”?
最佳答案
我会使用 .attr()
因为我更喜欢明确地知道我的目标是什么:
var customVal = $("#customInput").attr("value");
对于服务器端,请确保 ViewBag.SuccessBody
实际上已声明并返回一些内容。
public ActionResult FooAction()
{
ViewBag.SuccessBody = "This is a test";
return View();
}
还要确保您返回 ViewBag.SuccessBody
从正确的操作方法,到它对应的 View 。
更新
根据您的编辑:您正在重定向到不同的操作(编辑 [HttpGet]
操作),所以显然 ViewBag.SuccessBody
那里没有定义。为什么不直接传递 bool? editSuccess
参数到您的 [HttpGet]
编辑方法,提示是否编辑成功?
[HttpGet]
public ActionResult Edit(int id, bool? editSuccess)
{
if (editSuccess.HasValue)
{
if (editSuccess)
{
// edit was successful here
ViewBag.SuccessBody = "Yay! :)";
}
else
{
// edit was unsuccessful here
ViewBag.SuccessBody = "No! :(";
}
}
// other stuff
return View();
}
您的[HttpPost]
那么 Action 就变成了:
[HttpPost]
public ActionResult Edit(ArticleEditViewModel model)
{
if (ModelState.IsValid)
{
// ...
RedirectToAction("Edit", new { id = product.Id, editSuccess = true });
}
else
{
// ...
}
}
使用此方法,您还可以通过设置 editSuccess
来指定编辑何时可能失败。至false
。如果您只是想将任何值传递回 View ,请跳过所有 editSuccess
零件并简单返回 ViewBag.SuccessBody
来自[HttpGet]
操作,而不是 [HttpPost]
一个。
旁白:显然,如 editSuccess
是可选的,您只需设置 ViewBag.SuccessBody
当 editSuccess
时实际上有一个值,您可以在 View 中执行此检查以确定是否在 HTML 中输出某些内容:
@if (!string.IsNullOrEmpty(ViewBag.SuccessBody))
{
// not empty, do something
}
关于javascript - 如何从 View (MVC) 上的输入控件获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44630945/