我在代码背后写道。 但Viewbag.message将在警告消息中显示null .myvar是一个变量。 我使用断点,myvar将由Viewbag.message正确设置。但它会在警报中显示为空。
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
@{string myvar = ViewBag.AlertMessage;}
@using (Ajax.BeginForm("action", "controller", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
{
<script type="text/javascript">
function Messsage() {
alert('@ViewBag.AlertMessage'); //infact, it shows alert('');
}
</script>
答案 0 :(得分:0)
是在控制器操作中定义的ViewBag.AlertMessage
吗?
您可以通过
替换数据@{string myvar = "hello there !";}
<script type="text/javascript">
function Messsage() {
alert('@myvar'); // should show "hello there"
}
</script>
或在结果
后面的操作方法中定义您的viewbag项目public ActionResult Index() {
ViewBag.AlertMessage = "hello there !"
return View();
}
答案 1 :(得分:0)
<script type="text/javascript">
function Messsage() {
alert('@myvar'); // should show "hello there"
}
</script>
@using (Ajax.BeginForm("AjaxAction", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
{
<script type="text/javascript">
function Messsage() {
alert("@ViewBag.AjaxMessage");
}
</script>
<input type="submit" value="Submit" />
}
答案 2 :(得分:-1)
尝试在控制器操作中设置ViewBag.AlertMessage的值,该操作返回已定义Ajax.Begin表单的视图。
例如
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
ViewBag.AlertMessage = "AjaxMessage.";
return View();
}
}
在索引视图上我已经放置了以下代码,在Home Controller上调用了AjaxAction。
@using (Ajax.BeginForm("AjaxAction", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
{
<script type="text/javascript">
function Messsage() {
alert("@ViewBag.AjaxMessage");
}
</script>
<input type="submit" value="Submit" />
}