【问题标题】:How to show Jquery message in MVC from controller如何从控制器在 MVC 中显示 Jquery 消息
【发布时间】:2024-05-23 08:15:01
【问题描述】:

我正在使用 MVC,并且正在检查后端(控制器)上的条件。 我想在将从后端(控制器)触发的 Jquery 模式框中显示消息。

谁能告诉我如何做到这一点。

我尝试使用以下代码,但这给了我一些信息:无效参数。

string scriptstring = "$(function(){initializedialog();showDialog(\"" + "Please answer to all the Question." + "\");});";
            ScriptManager.RegisterStartupScript(this, typeof(Page), "test", scriptstring , true);

你能告诉我如何在MVC中使用上面的语句

谢谢

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-3 model-view-controller


【解决方案1】:

您可以使用 ajax 来执行此操作,因为 ssilas777 已注释掉。

使用以下 $.ajax 代码。

$(function(){
    $.ajax({
        url:'@Url.Action("Index","Home")',
        type: 'GET',
        dataType:'json',
        success:function(data){
            //Here you will get the data.
            //Display this in your Modal popup
        },
        error: function(data){
        }
    });
});

这是控制器代码。

public ActionResult Index(){
    //do some stuff
    string Message="your message here !";
    return Json(Message,JsonRequestBehaviour.AllowGet);
}

【讨论】:

  • 感谢 Karthik 我已经使用了这个选项,但我正在寻找一种可以显示来自控制器的消息的方法。
  • @Evostract - 你检查了 here also 吗?
【解决方案2】:

在 Controller 中,为其设置 ViewBag 标志,如下所示:

 ViewBag.Login = "No";

然后在查看检查 Document.Ready 是否已设置并在此处提供警报消息。

 <script>
$(document).ready(function () {
    varifyForLogin();
});
function varifyForLogin() {
    if ('@ViewBag.Login' == 'No') {
        //Give your alert message here
        alert('Please answer to all the Question.');
    }
    document.getElementById('UserName').focus();
}

【讨论】:

    【解决方案3】:

    在视图中的脚本中使用以下代码

    <script>
    $.post("Home/Index", function(result) {
    <br/>
        &nbsp;&nbsp;&nbsp;&nbsp;//result will be your message
    <br/>
    });
    </script>
    <br/>
    

    控制器:

    public ActionResult Index(){
    
        //do some stuff
        string msg="your message";
        return Json(msg,JsonRequestBehaviour.AllowGet);
    }
    

    【讨论】: