簡體   English   中英

在ajax調用中加載局部視圖

[英]Load Partial view in ajax call

我是MVC的新手。 我開始創建一個項目,但遇到了一個大問題。 請幫助我。 說明:我具有一個動作鏈接的視圖並加載一個局部視圖

@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)的簡單方法->從再次加載主頁的新視圖中加載新視圖,但仍保留在post視圖中)。

在主視圖中創建一個容器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);

          }

       });

按照此堆棧溢出答案https://stackoverflow.com/a/12006362/3541042中的指定,您可以將重定向URL發送回ajax回調並導航至該URL。

如果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>")';
        }
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM