简体   繁体   English

在ajax调用中加载局部视图

[英]Load Partial view in ajax call

I am new to MVC . 我是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 ). (从actionlink(post)的简单方法->从再次加载主页的新视图中加载新视图,但仍保留在post视图中)。

Make a container div in your main View: 在主视图中创建一个容器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>

and in your ajax call success function do this: 并在您的ajax调用成功函数中执行以下操作:

$.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. 按照此堆栈溢出答案https://stackoverflow.com/a/12006362/3541042中的指定,您可以将重定向URL发送回ajax回调并导航至该URL。

If the url is static, you can directly do it from java script itself as shown below. 如果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