Question

Can anyone please tell me how to retrieve formData in the controller method in ASP.net MVC?

<script type="text/javascript">
    $(function () {                 
        $('#fileupload').fileupload({
            contentType: 'application/json; charset=utf-8',
            url: '/Home/GoodSave'
        })
        .on("fileuploadsubmit", function (e, data) {
            data.formData = {
                jsonOfLog: $("#ddlDocumentType option:selected").text()
            };
        });

        $("#fileuploadbutton").on("click", function() {
            $("#fileupload").submit();
        });
    });
</script>
Was it helpful?

Solution

You usually specify a parameter in the controller action with the same name as the field in the form data:

[HttpPost]
public ActionResult GoodSave(string jsonOfLog)

Or define a model with corresponding field:

public class Form {
    public string jsonOfLog {get; set;}
}
[HttpPost]
public ActionResult GoodSave(Form data)

OTHER TIPS

I think you are trying to upload file using ajax. Use this link for uploading files via ajax.

However, below is the example of getting posted form data.

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="OK" />
}

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    // Verify that the user selected a file
    if (file != null && file.ContentLength > 0) 
    {
        // extract only the fielname
        var fileName = Path.GetFileName(file.FileName);
        // store the file inside ~/App_Data/uploads folder
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        file.SaveAs(path);
    }
    // redirect back to the index action to show the form once again
    return RedirectToAction("Index");        
}

Thanks U10 and Jefraim Ngek, by taking clues from your answers, I made it working this way:

In View:

<script type="text/javascript">
    $(function () {
            $('#fileupload').fileupload({
                dataType: 'json',
                url: '/Home/GoodSave', maxFileSize: 5000000,
                add: function (e, data) {
                    $("#fileuploadbutton").click(function () {                        
                        data.formData = { jsonOfLog: $("#ddlDocumentType option:selected").text() };
                        data.submit();
                    });
                },
            });
        });
</script>

In Controller method:

[HttpPost]
public JsonResult GoodSave(string jsonOfLog)
{
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top