![](/img/trans.png)
[英]ASP.Net MVC calling a controller action from FullCalendar's javascript function not loading the view
[英]Calling controller action from javascript in view
我想使用JavaScript從視圖中調用操作,但是我不能這樣做:這是我的代碼:
@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,但這未顯示損壞的腳本代碼和確認消息。 當我如下所示編寫它時: 從JavaScript調用ASP.NET MVC操作方法 :
@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>
}
沒有改變。 它顯示確認對話框,但不調用方法
除非您使用Ajax或其他客戶端機制與服務器對話,否則JavaScript無法調用控制器動作!
使用xhr綁定到服務器或使用以下jQuery代碼所需的內容
<script src='jquery-latest.js'></script>
@if (ViewBag.Status == true)
{
<script language="javascript" type="text/javascript">
if (confirm("Some message")){
//And here i want to add action call
$.get('@Url("action","controller",null)')
.done(function(data){
//use loaded data here
}).fail(function(e,f,g){
console.log({e:e,f:f,g:g})
});
}
</script>
}
PS:別忘了引用jQuery庫
如果我正確理解您的要求,則想從javascript中調用控制器中的Action方法。 並在成功時顯示確認消息。
這是該代碼:
if ('@ViewBag.Status' == true)
{
$.ajax({
type: "Post",
url: '@Url.Action("MyAction", "MyController")',
data: { Id: Id },
dataType: "json",
traditional: true,
success: function (data) {
alert("Success");
},
});
}
要獲得成功,您需要從控制器返回JsonResult或ContentResult或ActionResult。
您需要將代碼更改為如下所示,在這種情況下,您將調用: 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
同樣在控制器中,請記住在方法上應用[HttpPost]
屬性,如下所示:
[HttpPost]
public ActionResult MyAction(string id)
{
// your code
return Json();//your response
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.