在ajax调用中加载部分视图

时间:2014-04-22 10:19:57

标签: jquery ajax asp.net-mvc c#-4.0

我是MVC的新手。我开始创建一个项目,我面临一个大问题。 请帮助我。 说明:    我查看了一个actionlink并加载了一个局部视图

@model List<MuthuTag.Models.LoadPostModel>
@{
    ViewBag.Title = "LoadPost";
}

@Html.ActionLink("Add New Post","Post","Home")

<h2>LoadPost</h2>
<div>
    <table>
       @foreach (var Item in Model)
       {
        <tr>
            <td>
               @Item.TagId
            </td>
            <td>
                @Item.TagTitle
            </td>
            <td>@Item.TagContent</td>
        </tr>
       }
    </table>
</div>

在此你可以单击添加新的帖子操作链接,以便加载另一个视图 控制器代码

  public ActionResult Post()
        {
            return View();
        }

加载视图

@model MuthuTag.Models.LoadPostModel
@{
    ViewBag.Title = "Add New Post";
}
<script src="~/Content/jquery-1.8.3-min.js"></script>
<h2>Post</h2>
<link href="~/Content/magicsuggest-1.3.1.css" rel="stylesheet" />
<script src="~/Content/magicsuggest-1.3.1.js"></script>
<div id="Post">
    <table>
    <tr>
        <td>
              @Html.LabelFor(m => m.TagId)


        </td>
        <td>
                 @Html.TextBoxFor(m => m.TagId)
        </td>
        </tr>
          <tr>
        <td>
              @Html.LabelFor(m => m.TagTitle)


        </td>
        <td>
                    @Html.TextAreaFor(m => m.TagTitle)
        </td>
    </tr>
          <tr>
        <td>
              @Html.LabelFor(m => m.TagContent)


        </td>
        <td>
                  @Html.TextAreaFor(m => m.TagContent)
        </td>
    </tr>

       </table>
                <div id="ms-tpl"></div>


        <script type="text/javascript">            
            $('#ms-tpl').magicSuggest({
                width: 590,
                highlight: true,
                data: [{
                    id: 0,
                    name: "C#",
                    desc: "Server Code for all Web Applications in Microsoft Products",
                    //image: "images/panda.png"
                }, {
                    id: 1,
                    name: "ASP.Net",
                    desc: "Active Server Page that Holds Web Tech.",
                   // image: "images/butterfly.png"
                }, {
                    id: 2,
                    name: "Silverlight",
                    desc: "Sliverlight is the Microsoft Product with Great UI Design Sets",
                   // image: "images/dolphin.png"
                }, {
                    id: 3,
                    name: "MVC4",
                    desc: "Latest of all Microsoft Web Tech",
                   // image: "images/elephant.png"
                }, {
                    id: 4,
                    name: "PHP",
                    desc: "Light Weight Server Page",
                    //image: "images/hippo.png"
                }, {
                    id: 5,
                    name: "Sql",
                    desc: "Default Database Provider for Microsoft technologies",
                    //image: "images/turtle.png"
                }],
                renderer: function (v) {
                    return '<div>' +
                        '<div style="float:left;"><img src="' + v.image + '"/></div>' +
                        '<div style="padding-left: 85px;">' +
                            '<div style="padding-top: 20px;font-style:bold;font-size:120%;color:#333">' + v.name + '</div>' +
                            '<div style="color: #999">' + v.desc + '</div>' +
                            '</div>' +
                        '</div><div style="clear:both;"></div>';
                }
            });
        </script>   

         <input type="button" value="click" id="click"/>
        <input type="button" value="Save" id="Register" />
    </div>
  <div id="bind"></div>

        <script type="text/javascript">

                var jsonData = [];
                var ms1 = $('#ms-tpl').magicSuggest({
                    data: jsonData,
                    sortOrder: 'name',
                    maxResults: false
                });
                $('#Register').click(function () {
                    debugger;
                    var dataplus = ms1.getValue();
                    var tagid = document.getElementById('TagId').value;
                    var tagtitle = document.getElementById('TagTitle').value;
                    var tagcontent = document.getElementById('TagContent').value;
                    $.ajax({
                        url: '@Url.Action("GetPost")' + '?tagid=' + tagid + '&tagtitle=' + tagtitle + '&tagcontent=' + tagcontent + '&dataplus=' + dataplus,
                        type: 'POST',
                        cache: false,
                        success: function (data) {

                        }

                    });
                });

                $('#click').click(function () {
                    debugger;
                    alert(ms1.getValue());

                });

        </script>    

        [HttpPost]
        public ActionResult GetPost(Profile model)
        {
            SqlConnection con = new SqlConnection(conn);
            con.Open();
            string tagid = Request.Params["tagid"];
            string tagtitle = Request.Params["tagtitle"];
            string tagcontent = Request.Params["tagcontent"];
            SqlCommand cmd = new SqlCommand("CreatePostDetail", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@TagId", tagid);
            cmd.Parameters.AddWithValue("@TagContent", tagcontent);
            cmd.Parameters.AddWithValue("@TagTitle", tagtitle);
            //string name = Session["UserName"].ToString();
            string name = "123";
            cmd.Parameters.AddWithValue("@UserName", name);
            cmd.ExecuteNonQuery();
            con.Close();
            return View("Index");
        }

所以如果用户点击了保存按钮 它会进入控制器

[HttpPost]
        public ActionResult GetPost(Profile model)
        {
            SqlConnection con = new SqlConnection(conn);
            con.Open();
            string tagid = Request.Params["tagid"];
            string tagtitle = Request.Params["tagtitle"];
            string tagcontent = Request.Params["tagcontent"];
            SqlCommand cmd = new SqlCommand("CreatePostDetail", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@TagId", tagid);
            cmd.Parameters.AddWithValue("@TagContent", tagcontent);
            cmd.Parameters.AddWithValue("@TagTitle", tagtitle);
            //string name = Session["UserName"].ToString();
            string name = "123";
            cmd.Parameters.AddWithValue("@UserName", name);
            cmd.ExecuteNonQuery();
            con.Close();
            return View("Index");
        }

我返回索引,以便添加的内容显示在主页面中,但它仅保留在后视图中,但数据保存在数据库中。 (简单的方法 来自actionlink(post) - &gt;从中再次加载主页加载新视图,但它仍保留在帖子视图中。

2 个答案:

答案 0 :(得分:1)

在主视图中创建一个容器div:

@model List<MuthuTag.Models.LoadPostModel>
@{
    ViewBag.Title = "LoadPost";
}

@Html.ActionLink("Add New Post","Post","Home")

<h2>LoadPost</h2>
<div>
    <table>
       @foreach (var Item in Model)
       {
        <tr>
            <td>
               @Item.TagId
            </td>
            <td>
                @Item.TagTitle
            </td>
            <td>@Item.TagContent</td>
        </tr>
       }
    </table>
</div>
<div id="container">
</div>

并在你的ajax调用成功函数中执行此操作:

$.ajax({
         url: '@Url.Action("GetPost")' + '?tagid=' + tagid + '&tagtitle=' + tagtitle + '&tagcontent=' + tagcontent + '&dataplus=' + dataplus,
         type: 'POST',
         cache: false,
         success: function (data) {

         $('#container').html(data);

          }

       });

答案 1 :(得分:1)

如此堆栈溢出回答https://stackoverflow.com/a/12006362/3541042中所指定的,您可以将重定向URL发送回ajax回调并导航到该URL。

如果网址是静态的,您可以直接从java脚本本身执行此操作,如下所示。

$('#Register').click(function () {
    debugger;
    var dataplus = ms1.getValue();
    var tagid = document.getElementById('TagId').value;
    var tagtitle = document.getElementById('TagTitle').value;
    var tagcontent = document.getElementById('TagContent').value;
    $.ajax({
        url: '@Url.Action("GetPost")' + '?tagid=' + tagid + '&tagtitle=' + tagtitle + '&tagcontent=' + tagcontent + '&dataplus=' + dataplus,
        type: 'POST',
        cache: false,
        success: function (data) {
           window.location.href = '@Url.Action("Index", "<controller name>")';
        }
    });
});