Skip to main content
 首页 » 编程设计

c#之在 MVC4 表单提交后显示 Twitter Bootstrap 警报

2024年02月13日11jillzhang

我在 MVC 4.0 中有一个非常简单的表单,我的项目基于 bootstrap3 for MVC4 VS2012 模板。我想做的就是让用户提交表单,然后在我的 Controller 中进行一些验证,然后根据我传回给 View 的内容,它应该显示 Bootstrap 警报(错误或成功)

我已连接表单,以便在我单击“发送”时它会正确触发 Controller 上的正确操作。但我不确定以下事情:

  1. 如何隐藏警报,使其仅在我将结果返回到 View 后显示。
  2. 我希望显示错误或成功警报,我可以在 jQuery 中通过 .addClass 来实现吗?

![在此处输入图片描述][1]

[1]:

<div class="panel panel-info"> 
<div class="panel-heading"><strong>Register your interest</strong></div> 
<p></p> 
 
<div class="panel-body"> 
 
    <form name="contactform" class="form-inline" role="form" method="post" action="/Home/Contact"> 
 
        <div class="form-group"> 
            <label class="text-info">Name</label> 
            <input type="text" class="form-control" placeholder="Name"> 
        </div> 
        <p></p> 
        <div class="form-group"> 
            <label class="text-info">Email</label> 
            <input type="email" class="form-control" placeholder="Email"> 
        </div> 
        <p></p> 
        <div class="form-group"> 
            <label class="text-info">Comments</label><br /> 
            <textarea class="form-control" cols="20" rows="2" style="width: 400px; height: 150px; max-height: 350px; max-width: 500px"></textarea> 
        </div> 
        <p></p> 
 
        <button id="myBtn" type="submit" value="send" class="btn btn-primary">Send</button><p /> 
 
 
        <div class="alert alert-success" >              
            <strong>Thank you!</strong> Your query has been submitted.  
        </div> 
 
    </form> 
 
</div> 

请您参考如下方法:

我将首先建议您按照 Jonesy 上面的建议研究 ViewModels,但为了回答您的问题,一个简单的方法(可能不是最优雅的)是在您的 Controller 中设置一个 ViewBag 属性,例如:

... (code that validates data sent from view) 
ViewBag.TheResult = true; 
... 

然后,改变你的看法:

@if (ViewBag.TheResult == true) { 
<div class="alert alert-success" >              
    <strong>Thank you!</strong> Your query has been submitted.  
</div> 
} 

这将确保表单仅在您成功验证表单时显示警报。确保设置 TheResult 的值,即使它是负值,因为 View 期望在 ViewBag 中看到它。

至于你的第二个问题,你可以在没有 JQuery 的情况下以类似的方式解决它,只需在 ViewBag 中设置类的值并在标记中使用它。