0

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



    }
}
7
  • Currently your ajax call is wired up with the add button click, which does not do an ajax file upload, but a normal form submit, you will be doing a new GET to the Index page after that(because of the RedirectToAction method call). When do you want to show the partial view content ? When the Index page loads after successful upload (not an ajax file upload) ? Commented Jun 26, 2017 at 14:45
  • I have file upload through normal submit form and then I need to add some further content under my current view. Index page does not load after successful upload, it just shows a message. Do you suggest to do it differently? Commented Jun 26, 2017 at 14:54
  • Since it is a normal form submit, when you click on the submit button, the form will be submitted and the server returns a 302 response (for a new GET request to the Index page). When do you actually want to show your partial view result in this flow ? Commented Jun 26, 2017 at 14:56
  • Partial view should display right below the index view. Commented Jun 27, 2017 at 9:33
  • When ? After the index view gets (re) loaded after your normal form submit ? Commented Jun 27, 2017 at 14:51

1 Answer 1

1

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);

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.