zoukankan      html  css  js  c++  java
  • MVC从服务器端返回js到客户端的方法(总结)

    1、利用ViewBag,从服务器端创建一个显示js开关的ViewBag,然后到View中去做判断。

    Controller端

    [HttpPost]
            public ActionResult Index(hk_Admin model)
            {
                if (model.UserName != "xiaojie")
                {
                    ModelState.AddModelError("UserName", "用户名不正确。");
                }
                if (!ModelState.IsValid)
                {
                    ViewBag.msg = "error";
                }
                return View();
            }

    View端

    @{
        if(@ViewBag.msg == "error")
        {
            <script type="text/javascript">
                alert("请输入用户名");
            </script>
        }
    }
    </body>
    </html>

    个人感觉这种方式比较灵活,可以控制脚本在页面中的任何位置。

    2、直接在Controller中返回一个内容为脚本代码的Content

    [HttpPost]
            public ActionResult Index(hk_Admin model)
            {
                if (model.UserName != "xiaojie")
                {
                    ModelState.AddModelError("UserName", "用户名不正确。");
                }
                if (!ModelState.IsValid)
                {
                    return Content("<script >alert('请输入用户名');window.history.back(-1);</script >");
                }
                return View();
            }

    这种方法因为直接输出内容,所以不加后续处理(history.back或location)的话,页面会显示空白;

    3、在Controller中返回一个Javascript,使用这种方式的前提需要采用AJAX的方式,否则脚本无效。

    Controller端

    [HttpPost]
            public ActionResult Index(hk_Admin model)
            {
                if (model.UserName != "xiaojie")
                {
                    ModelState.AddModelError("UserName", "用户名不正确。");
                }
                if (!ModelState.IsValid)
                {
                    return JavaScript("请输入用户名");
                }
                return View();
            }

    View端部分代码

    @using (Ajax.BeginForm(new AjaxOptions()))
    {
    <div id="main">
        
        <div><img src="@baseUrl/login_top.gif" /></div>
        <div id="login_center">
        <table width="253" border="0" cellspacing="0" cellpadding="0" id="form_login">
      <tr>
        <td width="68" height="25" align="right" class="white">用户名:</td>
        <td width="120" height="25">
        <input type="text" class="input_text" name="UserName" id="UserName" />
        
        @Html.ValidationMessageFor(m => m.UserName)
        </td>
        <td height="25">&nbsp;</td>
      </tr>

    这种方式限制了必须使用ajax方式提交表单。

    还有其他的比如采用PartialView写脚本的方式,都大同小异。

  • 相关阅读:
    从gcc代码看go语言goroutine和channel实现
    /proc/$pid/maps文件中各个空间段的意义
    gdb通过frame切换栈帧之后寄存器是否准确
    ssh channel功能实现源码分析
    protobuf中extension的使用
    从反射看protobuf的部分实现
    最新JetBrains PyCharm 使用教程--常用功能设置(三)
    IntelliJ IDEA 中设置左菜单字体, 编辑器字体和控制台的字体
    最新JetBrains PyCharm 使用教程--安装教程(一)
    开源管理系统
  • 原文地址:https://www.cnblogs.com/superfeeling/p/4869111.html
Copyright © 2011-2022 走看看