经过多次努力,我提出了这个问题。我在页面上使用了剑道上传。能够在asyn模式下发布所选文件,页面包含Html.BeginForm。但是当我使用ajax请求将数据发送到控制器时,我无法将文件详细信息发送为 HttpPostedFileBase 。
以下是我的HTML
<form class="form-horizontal" role="form">
<div class="form-group">
@Html.Label("Complaint Name", new { @class = "col-sm-3 control-label" })
<div class="col-sm-4">
@Html.TextBoxFor(
m => m.ComplaintName,
new
{
@TabIndex = "1",
@class = "form-control input-sm",
disabled = true
})
</div>
</div>
<div class="form-group">
@Html.Label("Complaint Details", new { @class = "col-sm-3 control-label" })
<div class="col-sm-4">
@Html.TextBoxFor(
m => m.ComplaintDetails,
new
{
@TabIndex = "2",
@class = "form-control input-sm",
disabled = true
})
</div>
</div>
<div class="form-group">
@Html.Label("Choose files to upload", new { @class = "col-sm-3 control-label" })
<div class="col-sm-9 nopaddingforTextArea">
<input name="files" id="files" type="file" />
</div>
</div>
<div class="form-group">
<div>
<input id="btnSubmit" class="btn btn-primary pull-right" type="button" />
</div>
</div>
</form>
以下是我的行动
public ActionResult SaveComplaintDetails(string complaintName, string complaintDetails, IEnumerable<HttpPostedFileBase> files)
{
}
以下是我的js
$("#files").kendoUpload({
async: {
saveUrl: '@Url.Action("EsuperfundCommentsBind", ClientInboxConstants.NewQuery)',
autoUpload: false
},
multiple: true
});
$("#btnSubmit").click(function () {
//Ajax call from the server side
$.ajax({
//The Url action is for the Method FilterTable and the Controller PensionApplicationList
url: '@Url.Action("SaveComplaintDetails", "Complaints")',
//The text from the drop down and the corresponding flag are passed.
//Flag represents the Index of the value in the dropdown
data: {
complaintName: document.getElementById("ComplaintName").value,
complaintDetails: document.getElementById("ComplaintDetails").value,
files: //What to pass here??
},
contentType: "application/json; charset=utf-8",
//Json data
datatype: 'json',
//Specify if the method is GET or POST
type: 'GET',
//Error function gets called if there is an error in the ajax request
error: function () {
},
//Gets called on success of the Ajax Call
success: function (data) {
}
});
});
我的问题是如何将ajax中的Kendo Upload中的选定文件作为参数传递? 在这方面的任何帮助将非常感激。
答案 0 :(得分:0)
如果您的视图基于模型并且您已在<form>
标记内生成控件,则可以使用以下命令将模型序列化为FormData:
<script>
var formdata = new FormData($('form').get(0));
</script>
这还包括使用以下内容生成的所有文件:<input type="file" name="myImage" .../>
并使用以下内容将其发回:
<script>
$.ajax({
url: '@Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
</script>
并在您的控制器中:
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}
或(如果您的模型不包含HttpPostedFileBase的属性)
[HttpPost]
public ActionResult YourActionName(YourModelType model,
HttpPostedFileBase myImage)
{
}
如果您想添加表单中没有的其他信息,可以使用
添加<script>
formdata.append('someProperty', 'SomeValue');
</script>
示例用法:
查看:
@using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
@Html.LabelFor(m => m.FileAttachments, new { @class = "editor-label" })
@(Html.Kendo().Upload()
.HtmlAttributes(new { @class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '@Url.Action("Create", "Issue")',
data: formdata,
dataType: "json",
processData: false,
contentType: false,
success: function (response) {
//code omitted for brevity
}
});
});
});
</script>
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//code omitted for brevity
return Json(new { success = false, message = "Max. file size 10MB" }, JsonRequestBehavior.AllowGet);
}
希望这会有所帮助......
答案 1 :(得分:-2)
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#createDetail').get(0));
$.ajax(
{
type: 'POST',
url: '@Url.Action("Detail_Create", "Product")',
data: formdata,
processData: false,
success: function (result) {
if (result.success == false) {
$("#divErr").html(result.responseText);
} else {
parent.$('#CreateWindowDetail').data('kendoWindow').close();
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#divErr").html(xhr.responseText);
}
});
});
});
@using (Html.BeginForm("Detail_Create", "Product", FormMethod.Post, new { id = "createDetail", enctype="multipart/form-data"}))
{
<div id="divErr" class="validation-summary-errors"></div>
<fieldset>
<ol>
<li>
@Html.LabelFor(m => m.Price)
@(Html.Kendo().NumericTextBoxFor(m => m.Price).Name("Price").Format("{0:0}")
.HtmlAttributes(new { style = "width:100%" })
)
</li>
<li>
@Html.LabelFor(m => m.Description)
@Html.TextBoxFor(model => model.Description, new { @class = "k-textbox", id = "Description", style = "width:100%;" })
</li>
<li>
@Html.LabelFor(m => m.Group)
@(Html.Kendo().ComboBox()
.Name("Group")
.Placeholder("Введите группу детали")
.DataTextField("Name")
.DataValueField("Id")
.HtmlAttributes(new { style = "width:100%;" })
.Filter("contains")
.MinLength(1)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Group_Read_ComboBox", "Product");
})
.ServerFiltering(true);
})
)
</li>
<li>
@Html.LabelFor(m => m.Image)
@(Html.Kendo().Upload()
.Name("files")
)
</li>
</ol>
</fieldset>
<button type="submit" id="get" class="k-button">Добавить</button>
}
[HttpPost]
public ActionResult Detail_Create(DetailModel model, IEnumerable<HttpPostedFileBase> files)
{
string error = string.Empty;
if (ModelState.IsValid)
{
.....
}
IEnumerable<System.Web.Mvc.ModelError> modelerrors = ModelState.SelectMany(r => r.Value.Errors);
foreach (var modelerror in modelerrors)
{
error += "• " + modelerror.ErrorMessage + "<br>";
}
return Json(new { success = false, responseText = error }, JsonRequestBehavior.AllowGet);
}
按下按钮后,控制器null将出现如何修复。已经有2天了,时间结束了