0
我有一個ASP.Net MVC應用程序。我需要用ajax發送一個文件給Controller。但我有兩次要求。ASP.Net MVC AJAX上傳文件到控制器正在提交兩次
@using (Ajax.BeginForm("Create", "MyController", new { area = "" },
new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "onBegin",
OnSuccess = "onSuccess(data)"
}, new { enctype = "multipart/form-data", id = "myform" }))
{
<section class="col col-md-12">
@Html.DisplayFor(model => model.Title)
<label class="input">
@Html.TextBoxFor(model => model.Title)
</label>
</section>
<section class="col-md-6">
<label class="label text-left">
My File
</label>
<label for="file" class="input input-file">
<div class="button">
<input name="files" type="file" id="file" onchange=" this.parentNode.nextSibling.value = this.value ">choose...
</div>
<input type="text" readonly="" class="text-right">
</label>
</section>
<button type="submit" class="btn btn-primary">
Submit
</button>
}
控制器操作,當使用AJAX發佈我的數據時,這裏是我的Action中的兩次請求。
[HttpPost]
public ActionResult Create(HttpPostedFileBase files, CreateViewModel model)
{
// The Request comes here twice.
}
和我的頁面引用,
<script src="/Scripts/jquery.min.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="/Scripts/bootstrap/bootstrap.min.js"></script>
<script src="/Scripts/jquery.form.js"></script>
$(function() {
$('#myform').ajaxForm({
beforeSubmit: ShowRequest,
success: SubmitSuccesful,
error: AjaxError
});
});
function ShowRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
return true;
}
function AjaxError() {
alert("An AJAX error occured.");
}
function SubmitSuccesful(responseText, statusText) {
alert("SuccesMethod:\n\n" + responseText);
}
我應該怎麼辦?
不應該將按鈕類型從「提交」更改爲「按鈕」? – Kamo
不,沒關係 –
你有'Ajax.BeginForm()'做了一個ajax提交,然後你也有'$('#myform').ajaxForm()'做另一個ajax提交。將其更改爲'Html.BeginForm()' –