今天使用异步提交附件后台死活获取不到文件,代码还原
1 @using (Ajax.BeginForm("Add", "Event", new AjaxOptions() { HttpMethod = "Post", OnSuccess = "EntryFormJS.SubmitSuccess" }, new { id = "myform" })) 2 { 3 <div class="form-group"> 4 <label for="name">标题</label> 5 <input type="text" class="form-control" id="title" name="title" 6 placeholder="请输入标题"> 7 </div> 8 <div class="form-group"> 9 <label for="inputfile">封面图</label> 10 <input type="file" id="coverPic" name="coverPic"> 11 </div> 12 <div class="form-group"> 13 <div class="form-group"> 14 <label for="name">内容</label> 15 <textarea id="content" name="content" style="width:100%"></textarea> 16 </div> 17 </div> 18 <input type="hidden" id="id" name="id" /> 19 <div> 20 <button type="submit" class="btn btn-success" style="margin-left:200px">提交</button> 21 </div> 22 }
控制器使用 HttpPostedFileBase postedFile = Request.Files["coverPic"];接收数据,postedFile 值总是null。大脑暂时短路了,确实ajax提交表单中如果含有文件则无法获取。
后尝试使用jquery-form.js提交表单,后台获取到了附件。代码如下
html
1 @using (Html.BeginForm("Add", "Event", FormMethod.Post, new { enctype = "multipart/form-data" })) 2 { 3 <div class="form-group"> 4 <label for="name">标题</label> 5 <input type="text" class="form-control" id="title" name="title" 6 placeholder="请输入标题"> 7 </div> 8 <div class="form-group"> 9 <label for="inputfile">封面图</label> 10 <input type="file" id="coverPic" name="coverPic"> 11 </div> 12 <div class="form-group"> 13 <div class="form-group"> 14 <label for="name">内容</label> 15 <textarea id="content" name="content" style="width:100%"></textarea> 16 </div> 17 </div> 18 <input type="hidden" id="id" name="id" /> 19 <div> 20 <button type="button" onclick="submitData()" class="btn btn-success" style="margin-left:200px">提交</button> 21 </div> 22 }
js
1 var submitData = function () { 2 var content = $("#title").val(); 3 if (content.trim().length == 0) { 4 $.notify({ message: "请输入标题!", status: ‘warning‘, timeout: 2000 }).show(); 5 return false; 6 } 7 $(‘form‘).ajaxSubmit({ 8 type: "post", 9 url: "/Event/Add", 10 success: function (result) { 11 if (!result.error) { 12 $.notify({ message: "操作成功", status: ‘success‘, timeout: 2000 }).show(); 13 $(‘#eventModal‘).modal(‘hide‘) 14 $("#tableList").bootstrapTable(‘refresh‘); 15 } 16 else 17 $.notify({ message: result.msg, status: ‘warning‘, timeout: 2000 }).show(); 18 } 19 }); 20 }
时间: 2024-10-28 00:21:38