简体   繁体   中英

Load Partial view in ajax call

I am new to MVC . I started creating one project and i faced one big problem. pls help me with this. Explanation: I have view with one actionlink and loading one partial view

@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>

in this u can click the ADD new post action link so it ill load another view Controller code

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

It ill load a 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");
        }

so if user clicks the save button it will goes to the controller

[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");
        }

i return the index so that the added content ill display in the Main page but it remains in the post view alone but data saved in database. (simple way From actionlink(post) -->load new view from that again loading the home page but it remains in the post view ).

Make a container div in your main View:

@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>

and in your ajax call success function do this:

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

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

          }

       });

As specified in this stack overflow answer https://stackoverflow.com/a/12006362/3541042 you can send the redirection url back to the ajax call back and navigate to that URL.

If the url is static, you can directly do it from java script itself as shown below.

$('#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>")';
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM