Jakub Provazník
Jakub Provazník

Reputation: 29

asp.net mvc add partial view dynamically using ajax

I am new to ASP.NET and I have a problem to add a content to my main view. In HtmlBeginform I upload the file on a button click and after file loading I need to display partial view under my main view I don´t know how to call ajax script properly.

My main view:

@using prvniAplikace.Models;
@using Chart.Mvc.ComplexChart;
@using Chart.Mvc.Extensions;

@{
    ViewBag.Title = "Index";
}
@using (Html.BeginForm("LoadFile", "Home", FormMethod.Post,
                                                     new { enctype = "multipart/form-data" }))
{
    <div class="form-group" align="left">
        <label for="exampleInputFile">Load File</label>
        <input type="file" accept=".tcx" class="form-control-file" name="exampleInputFile" id="exampleInputFile" aria-describedby="fileHelp">
    </div>

    <div class="form-group" align="left">
        <button class="btn btn-primary" type="submit" id="add" name="add" value="Add">Display</button>
    </div>
}

@section Scripts {
    <script type="text/javascript">

        $("#add").on('click', function () {

            $.ajax({
                async: false,
                url: '/Home/getContent'
            }).success(function (partialView) {

                $('#getContent').append(partialView);

            });
        });

    </script>
}

View I want to add to a main view:

   @{
        ViewBag.Title = "getContent";
        Layout = null;
    }


    <h2>Obsah</h2>
    <p>Odstavec</p>
    <p>@DateTime.Now.ToString()</p>

Controller:

namespace prvniAplikace.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult getContent()
        {

            return PartialView("~/Views/Home/AjaxRequest.cshtml");
        }

        [HttpPost]
        public ActionResult LoadFile(HttpPostedFileBase exampleInputFile)
        {


            if (exampleInputFile.ContentLength > 0)
            {
                var fileName = Path.GetFileName(exampleInputFile.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                exampleInputFile.SaveAs(path);

                string xmlFile = Server.MapPath(fileName);

                XmlDocument doc = new XmlDocument();
                doc.Load(path);

                XmlNodeList nodes = doc.GetElementsByTagName("HeartRateBpm");
                XmlNodeList nodes2 = doc.GetElementsByTagName("Time");

            }
            return RedirectToAction("Index");
        }



    }
}

Upvotes: 0

Views: 993

Answers (1)

Shyju
Shyju

Reputation: 218722

As per your comment, you would like to load the partial view content via ajax after the index view is (re)loaded after the normal form submit you do to upload the file. To achieve this, you should make the ajax call in the document ready event. Since it is the same page/view user will see before and after the form submit, you should conditionally make the ajax call based on whether the page is loaded for your first GET request or for the GET request issued by the Redirect call in your http post action.

Since Http is stateless, there is no way for the GET action method to know whether this was called from the Redirect method call after successfully processing the submitted form (in your http post action). You may use TempData to address this problem. Before redirecting to the Index view, set a flag to the temp data dictionary which will be available in the next GET request.

[HttpPost]
public ActionResult LoadFile(HttpPostedFileBase exampleInputFile)
{
   // your existing code here
  TempData["Success"] = true;
  return RedirectToAction("Index");
}

Now in your GET action, read this and pass it to view via ViewBag (or a view model property if you have one)

public ActionResult Index()
{
    ViewBag.IsSuccess = TempData["Success"];
    return View();
}

Now in the view, check this ViewBag item and if it exist and has true value, render the div in which we want to show the partial view content. You can take advantage of the the Url.Action helper method to generate the correct relative path to the action method which returns partial view and keep that in html5 data attribute in the div tag so we can use that in javascript later to make the ajax call.

So add this to your index view.

@if (ViewBag.IsSuccess!=null && ViewBag.IsSuccess)
{
    <div data-url="@Url.Action("getContent", "Home")" id="myPartial"> </div>
}

Now all you need is the javascript code which makes the ajax call. Execute that in the document ready event. You can use the jQuery load method.

$(function(){
   // Get the url from the data attribute of the div
   var url = $("#myPartial").data("url");
   // Make the ajax call using load method
   $("#myPartial").load(url);

});

Upvotes: 1

Related Questions