0

I need to pass list of Objects. I am passing the data threw ajax call, ajax returns the results as expected, so the ajax call gets the correct results but partial view won't render.

Controller

[HttpPost]
public ActionResult GetXlFile()
{
    List<ListMatchDetails> lstPreview = new List<ListMatchDetails>();

    if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
    {
        var xlFile = System.Web.HttpContext.Current.Request.Files["FileToPreview"];
        HttpPostedFileBase filebase = new HttpPostedFileWrapper(xlFile);
        if (null != filebase && filebase.ContentLength > 0)
        {
            if (String.Compare(filebase.ContentType, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
            {
                using (Stream stream = filebase.InputStream)
                {
                    IExcelDataReader reader = null;

                    if (filebase.FileName.EndsWith(".xls"))
                    {
                        reader = ExcelReaderFactory.CreateBinaryReader(stream);
                    }
                    else if (filebase.FileName.EndsWith(".xlsx"))
                    {
                        reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                    }

                    reader.IsFirstRowAsColumnNames = true;
                    DataSet dsResult = reader.AsDataSet();
                    DataTable dtResult = dsResult.Tables[0];
                    if (dtResult.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dtResult.Rows)
                        {
                            ListMatchDetails lmd = new ListMatchDetails();
                            lmd.FirstName = (dr[0] != DBNull.Value) ? dr[0].ToString() : string.Empty;
                            lmd.LastName = (dr[1] != DBNull.Value) ? dr[0].ToString() : string.Empty;

                            lstPreview.Add(lmd);
                        }
                    }
                    reader.Close();
                }
            }
        }
    }

    return PartialView("_ExcelGrid", lstPreview);
}

view

@using app.Models;
@model IEnumerable<ListMatchDetails>

@{
    if (Model.Count() > 0)
    {
        ListMatchDetails row = Model.FirstOrDefault();
        <table class="table table-hover table-responsive scrollable table-striped ">
            <thead id="tableHeader">
                <tr>

                    <td>
                        @Html.LabelFor(x => row.FirstName)
                    </td>
                    <td>
                        @Html.LabelFor(x => row.LastName)
                    </td>

                </tr>
            </thead>
            <tbody class="pre-scrollable">

                @foreach (var record in Model)
                {
                    <tr>

                        <td>
                            @Html.ValueForModel(record.FirstName) 

                        </td>
                        <td>
                            @Html.ValueForModel(record.LastName)
                        </td>

                    </tr>
                }
            </tbody>
        </table>
    }
}

jquery:

$('#btnPreview').click(function () {
                var formData = new FormData();
                var files = $("#btnbrowse").get(0).files;
                if (files.length > 0) { formData.append("FileToPreview", files[0]); }
                $.ajax({
                    url: '/ListMatch/GetXlFile',
                    type: 'POST',
                    dataType: 'json',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (result) {
                        //$('#record').html(result)
                        $('._ExcelGrid').json(result);
                    },
                    error: function () {
                        //alert('Click Called');
                    }
                });
            });

4 Answers4

0

it looks like you need to use $('#record').html(result). Make sure you have something like

<div id="record">

</div>
0

Right off the bat comparing your action method to your jQuery ajax call, it looks like you're trying to parse the result of the ajax call as a JSON string but you're returning the _ExcelGrid partial view. Unless the _ExcelGrid partial view is returning valid JSON, that's going to break when it attempts to parse it as JSON.

I can't tell how it's supposed to be because I'm not sure what ._ExcelGrid is in your view, but generally speaking you can either change the action method to return JSON instead of a partial view and then parse/handle the JSON on the client side or assign the returned partial view to the element with $("._ExcelGrid").html(result). Which way you handle it is up to you.

If you opt to return the partial view, for completionist sake I'd change the dataType in your ajax call to html, because you're not expecting JSON anymore. You probably also want to set the contentType to the type of content that you're sending to the server, you can occasionally run into funny errors if you're not explict.

JosephRT
  • 545
  • 4
  • 19
0

This will get you past your roadblock. Please let me know if you want me to add more code pertaining to your question.

_ExcelGrid.cshtml

A Partial View

Controller:

public class HomeController : Controller
{
    [HttpPost]
    public PartialViewResult GetXlFile()
    {
        return PartialView("_ExcelGrid");
    }

    public ActionResult GetXlFile(int? id)
    {
        return View();
    }

View:

@{
    Layout = null;
}

<!DOCTYPE html>
@*credit to
https://stackoverflow.com/questions/5410055/using-ajax-beginform-with-asp-net-mvc-3-razor*@
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index800</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('form').submit(function (event) {
                $.ajax({
                    url: this.action,
                    type: "POST",
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#result').html(result);
                    }
                });
                return false;
            });
        });
    </script>
</head>
<body>
    <form>
        <div>
            @using (Html.BeginForm())
            {
                <input type="submit" value="OK" />
            }
            <div id="result"></div>
        </div>
    </form>
</body>
</html>
kblau
  • 2,094
  • 1
  • 8
  • 20
0

Greet for the day !!

Have you defined the partial view on your main page? if not you need to define partial view on your main page just like

<div id="dvExcelGrid">
    @Html.Partial("_ExcelGrid", "your model")
   </div>