如何在asp.NETMVC视图中回答JavaScript?

如何在asp.NETMVC视图中回答JavaScript?,javascript,c#,asp.net-mvc,Javascript,C#,Asp.net Mvc,我有以下代码: @if (!string.IsNullOrWhiteSpace(Model.ErrorMessage)) { <script> $('#modalError').modal('show'); </script> Response.Write("<script>alert('hello');</script>"); HttpContext.Current.Response.Write

我有以下代码:

@if (!string.IsNullOrWhiteSpace(Model.ErrorMessage))
{
    <script>
        $('#modalError').modal('show');
    </script>

    Response.Write("<script>alert('hello');</script>");

    HttpContext.Current.Response.Write("<script>alert('hello');</script>");
}

我想显示一条javascript消息,因为如果它是一个视图,我将使用模式引导,那么您最好使用javascript/JQuery。为此,您需要在HTML的某个地方添加一个隐藏字段,并将该值设置为
Model.ErrorMessage
。像这样:

<input type="hidden" id="hdError" value="@Model.ErrorMessage" />

然后在HTML正文的末尾添加Javascript代码:

<script>
$(function() {
    var errorStr = $("#hdError").val();
    if (errorStr) {
        alert("hello"); //or any other alert message
    } 
});
</script>

$(函数(){
var errorStr=$(“#hdError”).val();
if(errorStr){
警报(“你好”);//或任何其他警报消息
} 
});
@Alexandre Lima, 正如其他人在评论中指出的,我也同意,不确定你的方法是否正确,或者是否正确,那么我们需要更多的信息,也就是说,你有以下选择

  • 在视图模型上使用简单的数据验证来通知用户 一封无效的电子邮件-这是MVC为您内置的-MVC的数据 注释。这里是链接
  • 从您的评论来看,您似乎想在登录时显示一些内容 失败,意味着您的服务器代码返回时说
    Auth failed
    , 如果是这样的话,我假设你有这样的东西 在你的控制器代码上

    public ActionResult Login(LoginModel login)
    {
       if(ModelState.IsValid)
       {
          //you call your service to get back the result
    
          if(!NotAValidUser)
          { 
             ModelState.AddModelError("LoginFailed", "The user name and or password is incorrect.")
          }
       }
    }
    
    在你看来


  • 您共享的代码在哪里?它是在视图中还是在动作方法中?我们需要这些信息才能正确地帮助您。还有,为什么要输出带有Response.Write()的脚本标记?我们需要知道您试图实现什么。@Botonomous,要向用户发送消息,“name或invalid email”@SomadinaMbadiwe这是一个视图如果您将验证构建到视图模型中,您可以通过在模型上使用MVC注释来进行简单的验证,并在视图中适当地反映它们——这里有一个链接可能有助于我使用javascript显示模式引导
    <script>
    $(function() {
        var errorStr = $("#hdError").val();
        if (errorStr) {
            alert("hello"); //or any other alert message
        } 
    });
    </script>
    
    public ActionResult Login(LoginModel login)
    {
       if(ModelState.IsValid)
       {
          //you call your service to get back the result
    
          if(!NotAValidUser)
          { 
             ModelState.AddModelError("LoginFailed", "The user name and or password is incorrect.")
          }
       }
    }
    
    @Html.ValidationMessage("LoginFailed") // this will display the above message