首页 新闻 会员 周边

一个小例子后端是MVC,各位大师指点一下怎么用jquery交互

0
悬赏园豆:20 [已解决问题] 解决于 2014-07-22 14:26

比如我有一个例子:

一张User表;有三个字段:ID,Name,Age

用的是EF实体框架

后端MVC的控制器代码(一个查询所有,一个增加):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlogUI.Models;
namespace BlogUI.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult Index()
        {
            return View();
        }
        
       BlogDAL.BlogEntities db = new BlogDAL.BlogEntities();

        public ActionResult GetUserList() {
            var result=db.User.ToList();
            return View(result);
        }

        public ActionResult AddUser(User u) {
            User obj = new User();
            obj.ID = 0;
            obj.Name = u.Name;
            obj.Age = u.Age;
            db.SaveChanges();
            return View();
        }

    }
}
View Code

视图代码:

@{
    ViewBag.Title = "Index";
}

<table>
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>年龄</th>
    </tr>
</table>

<form method="post">
    <table>
        <tr>
            <td>姓名</td>
            <td>
                <input type="text" /></td>
        </tr>
        <tr>
            <td>年龄</td>
            <td>
                <input type="text" /></td>
        </tr>
        <tr>
            <td>
                <input type="submit" value="提交" /></td>
        </tr>
    </table>
</form>
View Code

这样的话我查询所有信息向前台展示时该怎么写JS交互?
增加的时候又是怎样写JS向后端交互?

看了网上许多例子,但是没有切合实际的,还是不太懂

求各位的按照我的小例子,写个细致易懂的代码

万分感谢!

骑着蜗牛耍流氓的主页 骑着蜗牛耍流氓 | 初学一级 | 园豆:135
提问于:2014-07-22 11:32
< >
分享
最佳答案
0
var postData = $("#MyForm").serializeArray();
            $.ajax({
                url: "/Administrator/AddArticle",
                type: "POST",
                cache: false,
                dataType: "text",
                data: postData,
                success: function (rtn) {
                    if (rtn == "OK") {

                        alert("文章添加成功!");
                        $('#div_add').dialog('close');
                        $("#dg_list").datagrid("reload");

                    } else {
                        alert("文章添加失败!");
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest.status);
                    alert(XMLHttpRequest.readyState);
                    alert(textStatus);
                }
            });

类似这种,自己改下试试吧。

收获园豆:20
Alex_QY1987 | 小虾三级 |园豆:1888 | 2014-07-22 13:04

好,谢了

骑着蜗牛耍流氓 | 园豆:135 (初学一级) | 2014-07-22 13:39

那 前台获取后台列表该怎么写呢

骑着蜗牛耍流氓 | 园豆:135 (初学一级) | 2014-07-22 13:46

@骑着蜗牛耍流氓: 获取后台列表是怎么个意思?

如果你后台返回的是个列表对象,那就把它用JSON的方式返回,然后在前台Ajax的success:function(jsonStr){

//在这里去解析JSON对象,做相关处理

}

Alex_QY1987 | 园豆:1888 (小虾三级) | 2014-07-22 17:11

@Alex_QY1987: 好的  知道啦

骑着蜗牛耍流氓 | 园豆:135 (初学一级) | 2014-07-22 17:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册