ASP.NET MVC 4 Web アプリケーションを開発しています。私はWebアプリケーションの初心者です。私の問題は、ファイルのアップロードと ajax にあります。私は2つのフォームを持っています。1 つは、ユーザーから名前、家族などのデータを取得するためのものです。もう1つは画像をアップロードすることです。ユーザーが登録を送信する前に画像をアップロードし、アップロードされた画像を<img>
タグで表示できるようにしたい。これが私のコードです:
意見
@using (Html.BeginForm("Register", "Customer", FormMethod.Post))
{
<fieldset>
<div class="control-group">
<label class="control-label">Name</label>
<div class="controls">
@Html.TextBoxFor(model => model.Name)
</div>
</div>
<div class="control-group">
<label class="control-label">Family</label>
<div class="controls">
@Html.TextBoxFor(model => model.Family)
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Submit" class="btn btn-info"/>
</div>
</div>
</fieldset>
}
<img src="" class="img"/>
@using (Html.BeginForm("UploadImage", "Customer", FormMethod.Post, new { d="ImageUploadForm", @enctype = "multipart/form-data" }))
{
<input type="file" name="imgfile" class="imgfile"/>
<input type="submit" value="Upload" class="btnUpload btn btn-info" />
}
アクションインコントローラー
[HttpPost]
public string UploadImage(HttpPostedFileBase imgfile)
{
string filePath = "";
if (imgfile != null && imgfile.ContentLength > 0)
{
filePath = Path.Combine(Server.MapPath("~/Customer/"), imgfile.FileName);
imgfile.SaveAs(filePath);
}
return "~/Customer/" + imgfile.FileName;
}
Javascript
$('#ImageUploadForm').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('.img').attr('src', result);
}
})
return false;
}
});
問題は、ファイルを選択してUpload
ボタンを押すと、アクションが呼び出されてファイルがアップロードされるのですが、ajax の成功イベントが呼び出されず、そのコンテンツUploadImage()
と呼ばれる別のページにリダイレクトされるということです。戻ってきた。これを行うことは可能ですか?または、別のページにリダイレクトせずに ajax を使用してフォーム データを投稿することはできませんか? どんな助けでも大歓迎です。localhost/Customer/UplaodImage
UploadImage