Ajax表单在CSV上载时返回null

时间:2018-02-16 19:27:00

标签: asp.net ajax asp.net-mvc asp.net-mvc-partialview

这是设置的方式, - 有一个视图,可以上传CSV - 有一个控制器部分视图操作,它应该检索解析CSv并从CSV读取对象并将其传递回PArtial View。 - 部分视图比支持在页面上呈现所有记录。

但显然bulkClients对象显示为null。

这是控制器: -

public ActionResult UploadBulkClients()
    {
        return View();
    }

//    [HttpPost]
    public PartialViewResult _UploadBulkClients(HttpPostedFileBase bulkClients) 
    {
        if (bulkClients != null)
        {
            try
            {
                StreamReader reader = new StreamReader(bulkClients.InputStream);
                while (reader != null)
                {
                    var csv = new CsvReader(reader);
                    csv.Read();
                    csv.ReadHeader();

                    while (csv.Read())
                    {
                        newRecord.Add(new ClientAgencyViewModel()
                        {
                            Id = UrbanLighthouse.Shared.Statics.NewUniqueGUID(),
                            ReferenceNo = csv["ReferenceNo"].ToString(),
                            FirstName = csv["FirstName"].ToString(),
                            MiddleName = csv["MiddleName"].ToString(),
                            LastName = csv["LastName"].ToString(),
                            StreetAddress = csv["StreetAddress"].ToString(),
                            City = csv["City"].ToString(),
                            PostalCode = csv["PostalCode"].ToString(),
                            Province = Guid.Parse(csv["Province"].ToString()),
                            Phone = csv["Phone"].ToString(),
                            Email = csv["Email"].ToString()
                        });
                    }
                    foreach (var item in newRecord)
                    {
                        if (repository.DoesEmailExist(item.Email) == true)
                        {
                            item.Email = item.Email + " : " + "Invalid Email Address";
                        }
                        else
                        {
                            item.Email = item.Email + " : " + "This Email is Good";
                        }
                    }
                }
                return PartialView(newRecord);
            }
            catch (System.IO.IOException e)
            {
                return PartialView(e);
            }
        }
        else
        {
            newRecord.Add(new ClientAgencyViewModel()
            {
                ReferenceNo = "Empty",
                FirstName = "Empty",
                MiddleName = "Empty",
                LastName = "Empty",
                StreetAddress = "Empty",
                City = "Empty",
                PostalCode = "Empty",
                Province = Guid.Empty,
                Phone = "Empty",
                Email = "Empty"
            });
            return PartialView(newRecord);
        }
    }

以下是View的布局: -                 @model字符串                 @ {                     Layout =“〜/ Views / Shared / _LayoutAnonymous.cshtml”;                     AjaxOptions选项=新的AjaxOptions                     {                         UpdateTargetId =“uploadList”,                         InsertionMode = InsertionMode.Replace,                         HttpMethod =“POST”                     };                 }

            <div>
                @using (Ajax.BeginForm("_UploadBulkClients", "Client",options, new { enctype = "multipart/form-data" , role = "form", @class = Css.Form, @id = "formLogin" , action = "/Client/_UploadBulkClients" }))
                {
                <div class="@Css.FormGroup">
                    <h1>Client Bulk Upload</h1>

                    <div class="@Css.InputGroup">
                        <label>Upload CSV File</label>
                        <input type="file" name="postedFile" />
                    </div>

                    <div class="@Css.InputGroup">
                        @Html.Submit("Submit")
                    </div>

                </div>
                }
            </div>

            <div>
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Reference No</th>
                            <th>FirstName</th>
                            <th>MiddleName</th>
                            <th>LastName</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>StreetAddress</th>
                            <th>City</th>
                            <th>PostalCode</th>
                            <th>Province</th>
                        </tr>
                    </thead>
                    <tbody id="uploadList">
                        @Html.Action("_UploadBulkClients","")
                    </tbody>
                </table>

            </div>

当HttpPost装饰器留在PartialView方法之上时,它在视图@Html.Action("_UploadBulkClients","")中给出错误,表示_UploadBulkClients Action方法不存在。

编辑: - 似乎上传不是发布csv文件,我不明白为什么会这样,因为Ajax表单看起来应该是这样的。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

在Stephen的帮助下,我能够找到答案,必须使用JavaScript而不是C#中的AjaxOptions。

以下是有人遇到类似事情的步骤: -  1.控制器方法,返回表单

    public ActionResult UploadBulkClients()
    {
        return View();
    }

2。表单必须是一个简单的表单,而不是Ajax表单。我在这里使用了Html Helpers:

@using (Html.BeginForm("_UploadBulkClients", "Client",null, FormMethod.Post , new { enctype = "multipart/form-data" , role = "form", @class = Css.Form, @id = "uploadForm" }))
{
<div class="@Css.FormGroup">
    <h1>Client Bulk Upload</h1>

    <div class="@Css.InputGroup">
        @Html.LabelFor(m=>m.File)
        @Html.TextBoxFor(m=>m.File, new { type= "file"})
    </div>

    <div class="@Css.InputGroup">
        @Html.Submit("Submit")
    </div>

</div>
}

 3.下一部分是返回局部视图的控制器方法。

    [HttpPost]
    public PartialViewResult _UploadBulkClients(HttpPostedFileBase file) 
    {
        if (file != null)
        {
            try
            {
                using (var reader = new StreamReader(file.InputStream))
                using (var csv = new CsvReader(reader))
                {
                    csv.Read();
                    csv.ReadHeader();
                    while (csv.Read())
                    {                        
                        newRecord.Add(new ClientAgencyViewModel()
                        {
                               Id = UrbanLighthouse.Shared.Statics.NewUniqueGUID(),
                               ReferenceNo = csv["ReferenceNo"],
                               FirstName = csv["FirstName"].ToString(),
                               MiddleName = csv["MiddleName"].ToString(),
                               LastName = csv["LastName"].ToString(),
                               StreetAddress = csv["StreetAddress"].ToString(),
                               City = csv["City"].ToString(),
                               PostalCode = csv["PostalCode"].ToString(),
                               ProvinceText = csv["Province"].ToString(),
                               Phone = csv["Phone"].ToString(),
                               Email = csv["Email"].ToString()
                        });
                    }
                    foreach (var item in newRecord)
                    {
                        if (repository.DoesEmailExist(item.Email) == true)
                        {
                            item.Email = item.Email + " : " + "Email Address Already Exists";
                        }
                        else
                        {
                            item.Email = item.Email + " : " + "This Email is Good";
                        }
                    }
                }
                return PartialView(newRecord);
            }
            catch (System.IO.IOException e)
            {
                return PartialView(e);
            }
        }
        else
        {
            newRecord.Add(new ClientAgencyViewModel()
            {
                ReferenceNo = "Empty",
                FirstName = "Empty",
                MiddleName = "Empty",
                LastName = "Empty",
                StreetAddress = "Empty",
                City = "Empty",
                PostalCode = "Empty",
                ProvinceText = "Empty",
                Phone = "Empty",
                Email = "Empty"
            });
            return PartialView(newRecord);
        }
    }

4。下一部分是部分视图,它呈现控制器方法的输出。

  @model List<WebPlatform.ViewModels.ClientAgencyViewModel>
  @foreach (var item in Model)
  {
<tr>
    <td>@item.ReferenceNo</td>
    <td>@item.FirstName</td>
    <td>@item.MiddleName</td>
    <td>@item.LastName</td>
    <td>@item.Phone</td>
    <td>@item.Email</td>
    <td>@item.StreetAddress</td>
    <td>@item.City</td>
    <td>@item.PostalCode</td>
    <td>@item.ProvinceText</td>
</tr>
   }

5。最后但并非最不重要的是在JavaScript中编写的Ajax功能,因为AjaxOptions在这种特殊情况下不起作用。

$('#uploadForm').submit(function(e) {
e.preventDefault();
var formdata = new FormData($(this).get(0));
$.ajax({
    url: '@Url.Action("_UploadBulkClients","Client")',
    type: 'POST',
    data: formdata,
    processData: false,
    contentType: false,
    success: function (response) {
        $('#uploadList').html(response);
     }
   },

  );
});