0

I try to upload file using MVC4 syntax

@using (Html.BeginForm("ImportCsv","ASPolicy", FormMethod.Post, new {enctype = "multipart/form-data"}))
            {
                <input type="file" name="file" style="display: none"/>
                <input type="text" name="cid" value="'@ViewData["cid"]'" style="display: none"/>
                <input type="submit" value="upload" style="display: none"/>
            }

and my controller look like

public JsonResult ImportCsv(HttpPostedFileBase file, String cid)
    {

        IPRestriction ipRestriction = new IPRestriction();
        List<string> ipList = new List<string>();

        using (BinaryReader b = new BinaryReader(file.InputStream))
        {
            byte[] binData = b.ReadBytes(Convert.ToInt32(file.InputStream.Length));
            string result = System.Text.Encoding.Unicode.GetString(binData);

            TextReader textReader = new StringReader(result);
            CsvReader csv = new CsvReader(textReader, new CsvConfiguration() {Delimiter = "\t"} );

            while (csv.Read())
            {
                string accountNumber = csv.GetField(0);
                string ip = csv.GetField(1);
                ipRestriction.accountNumber = accountNumber;
                ipList.Add(ip);
            }

            ipRestriction.ipAllowList = ipList.ToArray();
        }

        String jsonStr = JsonConvert.SerializeObject(ipRestriction);
        return Json(jsonStr, JsonRequestBehavior.AllowGet);
    }

This one seen to be not work because all time time submit button is clicked, it will fall to this controller and try to redirect page with json I have return.

So, there is anyway to upload file and get json response, I need to use this json response to render content in this page

  • 1
    What you need to do is to submit the form asynchronously. Perhaps using `jQuery.Post`. If you submit the form the way you are doing now you will get redirected to a JSON string page. Refer to this blog: http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/ – Rosdi Kasim Apr 11 '14 at 08:32
  • See this link: http://stackoverflow.com/questions/5193842/file-upload-asp-net-mvc-3-0 – Ibrahim Khan Apr 11 '14 at 08:43

1 Answers1

0

You need ajax post instead of Html.BeginForm(). So, use jquery forms plugin and Ajax.BeginForm() which makes the task so easy. Here are the steps.

Include Libraries

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

View

//Returned Json value will be here.
<div id="result"></div>

@using (Ajax.BeginForm("ImportCsv", "ASPolicy", new AjaxOptions() { HttpMethod = "POST" , UpdateTargetId = "result" }, new { enctype = "multipart/form-data"}))
{
    @Html.AntiForgeryToken()
    <input type="file" name="files"><br>
    <input type="submit" value="Upload File to Server">
}

Controller

public JsonResult ImportCsv(IEnumerable<HttpPostedFileBase> files, String cid)
{
    if (files != null)
    {
        foreach (var file in files)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // TODO: need to define destination
                var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                file.SaveAs(path); //upload for example
            }
        }
    }

    //String jsonStr = JsonConvert.SerializeObject(ipRestriction);
    return Json(jsonStr, JsonRequestBehavior.AllowGet); //Now return Json as you need.
}
Community
  • 1
  • 1
Ashwini Verma
  • 7,477
  • 6
  • 36
  • 56