我想使用 JavaScript 从 View 中调用操作,但我不能这样做: 这是我的代码:
@if (ViewBag.Status == true)
{
<script language="javascript" type="text/javascript">
if (confirm("Some message"));
//And here i want to add action call
</script>
}
我正在尝试使用@Html.Action,但是这个损坏的脚本代码和确认消息没有显示。 当我如下所示编写它时:Calling ASP.NET MVC Action Methods from JavaScript :
@if (ViewBag.Status == true)
{
<script language="javascript" type="text/javascript">
if (confirm("Some message"));
{
$.ajax({
url: 'MyController/MyAction',
data: { id: id },
success: function () {
alert('Added');
}
});
}
</script>
}
没有任何改变。它显示确认对话框但不调用方法
最佳答案
您需要将代码更改为类似这样的内容。在这种情况下,您将调用:func(@ViewBag.Status)
@Section scripts
<script language="javascript" type="text/javascript">
//val in this case being the value of the ViewBag passed from where the call is occurring
function func(val) {
if (val == true) {
if (confirm("Some message"));
{
$.ajax({
url: 'MyController/MyAction',
data: { id: id },
type: "POST",
success: function () {
alert('Added');
}
});
}
}
}
</script>
end section
同样在 Controller 中记得在方法上应用 [HttpPost]
属性,如下所示:
[HttpPost]
public ActionResult MyAction(string id)
{
// your code
return Json();//your response
}
关于javascript - 从 View 中的 javascript 调用 Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30191179/