一、MVC+EF控制器和后台交互

一、后台控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCDemo.Controllers
{
    public class AccountController : Controller
    {
        // GET: Account
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Login()//这个是默认HTTP Get请求的Action,用于显示页面
        {
            ViewBag.LoginState = "登录前。。。";
            return View();
        }
        [HttpPost]
        public ActionResult Login(FormCollection fc)//这个同名的Action 应用HttpPost 属性  接受用户传来的数据
        {
            string email = fc["email"];
            string password = fc["password"];
            //实例化数据库上下文
            MVCDemo.Models.Model1 db = new Models.Model1();
            //使用Lambda表达式查询数据
            var user = db.Users.Where(o=>o.Name=="Admin").ToList();
            //Linq语句查询(函数式) var user1 = from o in dbcontext.Userwhere o.Name == "qiumuxiaq141813"  select o;
            ViewBag.LoginState = user.First().Name+user.First().Password + "登陆后。。。";
            return View();
        }
        public ActionResult Register()
        {
            return View();
        }
                // GET: Login
        public ActionResult Login() //session的使用
        {
            Session["name"] = "hello";
            return Redirect("/Index/Index");
        }
        
        public ActionResult Del(int id) //删除方法
        {
            try
            {
                //1、创建要删除的对象
                Slide DelSlide = new Models.Slide() { SildeId = id };
                //2、将对象添加到EF管理容器中
                db.Slides.Attach(DelSlide);
                //3、将对象包装类的状态标识为删除状态
                db.Slides.Remove(DelSlide);
                //4、更新到数据库
                db.SaveChanges();
                return RedirectToAction("Slide", "Slide");//重新定向到HomeController的Index()方法,就是重新加载一下数据
            }
            catch (Exception ex)
            {
                return Content("删除失败!!!" + ex.Message);
            }

        }


        [HttpPost]
        public ActionResult EditSlide(HttpPostedFileBase previewImg,FormCollection fc) //上传图片
        {
            string name = fc["pic"];
            string show_link= fc["show_link"];
            string SlideSort = fc["SlideSort"];
            string fileName = previewImg.FileName;       
            if (fileName.LastIndexOf("\\") > -1)
            {
                fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
            }
            previewImg.SaveAs(Server.MapPath(fileName));
            Response.Write("<script>alert('图片已经上传成功!!!!');</script>");
            using (var tmpDB = new CMSEntities())
            {
               Demo.Models.Slide AddSlide = new Slide { SildeName = name,SildeHref=show_link,SildeDes=SlideSort,SildePic= "/Slide/"+fileName };
                db.Slides.Add(AddSlide);
                db.SaveChanges();
            };
            var slider = db.Slides.ToList();
            return View(slider);
        }


    }
}

二、前台页面

<body>
    <div>
        @ViewBag.LoginState
    </div>
    <div class="wrapper">
        @*  使用HtmlHelper 来替换   <form action="/account/login" method="post" role="form"> </form>  达到动态计算路由地址的一种方式*@
        @using (Html.BeginForm("login", "account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
        {
            <div class="loginBox">
                <div class="loginBoxCenter">
                    <p><label for="username">电子邮箱:</label></p>
                    <p><input type="email" id="email" name="email" class="loginInput" autofocus="autofocus" required="required" autocomplete="off" placeholder="请输入电子邮箱" value="" /></p>
                    <p><label for="password">密码:</label><a class="forgetLink" href="#">忘记密码?</a></p>
                    <p><input type="password" id="password" name="password" class="loginInput" required="required" placeholder="请输入密码" value="" /></p>
                </div>
                <div class="loginBoxButtons">
                    <input id="remember" type="checkbox" name="remember" />
                    <label for="remember">记住登录状态</label>
                    <button class="loginBtn">登录</button>
                </div>
            </div>
        }

    </div>

</body>
        $(function(){
            $('.submit-btn').click(function () {
                //$('.login-input').val();
                //$('.pass-input').val();
                $.ajax({
                    url:'/Login/Login',
                    type:'post',
                    dataType:'json',
                    timeout:1000,
                    success: function (data, status) {
                        console.log(data)
                    },
                    fail: function (err, status) {
                        console.log(err)
                    }
                });
            });
        });

//第一种写法(参数写成json数据形式)

                $.ajax({
                    url: 'http://api.chongfa.cn/v8/user/login',
                    method: 'get',
                    dataType: 'json',
                    data: {
                        phone: '13655202412',
                        password: '123'
                    },
                    success: function (data) {
                        alert(JSON.stringify(data));
                        console.log(JSON.stringify(data));
                    }, error: function (err)
                    {
                        alert(JSON.stringify(err));
                        console.log(JSON.stringify(err));
                    }
                });

//第二种写法(把参数拼接在URL中,data属性设为空{ }

                $.ajax({
                    url: 'http://api.chongfa.cn/v8/user/login',
                    method: 'get',
                    dataType: 'json',
                    data: "phone=" + $(".login-input").val() + "&password=" + $(".pass-input").val(),
                    success: function (data) {
                        alert(JSON.stringify(data));
                        console.log(JSON.stringify(data));
                    }, error: function (err)
                    {
                        alert(JSON.stringify(err));
                        console.log(JSON.stringify(err));
                    }
                });
首先我觉得action的跳转大致可以这样归一下类,跳转到同一控制器内的action和不同控制器内的action、带有参数的action跳转和不带参数的action跳转。

一、RedirectToAction("Index");//一个参数时在本Controller下,不传入参数。

二、RedirectToAction(ActionName,ControllerName) //可以直接跳到别的Controller.

三、RedirectToRoute(new {controller="Home",action="Index"});//可跳到其他controller

四、RedirectToRoute(new {controller="Home",action="Index", id=param});//可跳到其他controller,带参数。

五、Response.Redirect("Index?id=1");//适用于本controller下的方法名称,可带参数。
六、return Redirect("Index");//适用于本controller下的方法名称。

七、return View("Index"); //直接显示对应的页面 不经过执行Controller的方法。 
八、return View("~/Views/Home/Index.aspx");//这种方法是写全路径,直接显示页面,不经过Controller方法
九、return View();//直接显示页面,不经过Controller方法
//RedirectToAction(view?参数,控制器);
return RedirectToAction("MyjoinEvent?id=" + eventid + "&type=6", "Event");
// 显示提示框,并返回上一页
return Content("<script>alert('暂时没有实践作业!');history.go(-1);</script>");
// Redirect("/控制器/视图?参数");
return Redirect("/MyCourse/Xinde_ck?event_id=" + eventid + "&T=" + T + "");
//RedirectToAction("视图",new { 参数 });
return RedirectToAction("sj_homeworklist", new { eventtype = 1 });
//RedirectToAction(view?参数,控制器);
return RedirectToAction("MyjoinEvent?id=" + eventid + "&type=6", "Event");
当用Redirect或者RedirectToAction的时候,尽量使用false参数。

return Response.Redirect(url1, false);
return RedirectToAction("Index", "Home", false);
return Redirect("/Index/Index", false);
在网页浏览的时候,有可能因为没有false导致网页线程中断。(猜测,没证据)

//返回的是view页面,不会再走Controller
return View("Index");

---------------------

本文来自 夜雪CH 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/changhong009/article/details/61664501?utm_source=copy 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力吧少年-珊珊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值