【问题标题】:Having two forms in ASP.NET MVC 4 and posting one of them with ajax在 ASP.NET MVC 4 中有两种形式并使用 ajax 发布其中一种
【发布时间】:2013-08-11 03:17:56
【问题描述】:

我正在开发一个 ASP.NET MVC 4 Web 应用程序。我是 Web 应用程序的初学者。我的问题是文件上传和ajax。我有两种形式。其中之一是从用户那里获取数据,例如姓名、家庭等。另一种是上传图片。我希望用户能够在提交注册之前上传图片,并在<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 按钮时,会调用UploadImage() 操作并上传文件,但是没有调用ajax 的成功事件,它会将我重定向到另一个名为localhost/Customer/UplaodImage 它的内容就是UploadImage 返回的文件路径。有可能做到这一点吗?或者我不能使用 ajax 发布表单数据而不重定向到另一个页面?任何帮助表示赞赏。

【问题讨论】:

    标签: c# asp.net jquery asp.net-mvc-4 file-upload


    【解决方案1】:

    据我所知,您不能通过常规 AJAX 发布文件。使用一些辅助库:FileUploader 等...

    更新:

    Adeelthis 回复:

    XHR2 支持通过 AJAX 上传文件。例如。通过 FormData 对象,但不幸的是它不被 all/old 支持 浏览器。

    【讨论】:

    • 上传工作正常,文件已上传。问题是它将我重定向到另一个页面。我想留在注册页面。
    • 那是因为请求无法成功完成!仅当您收到200 (OK) 响应时,请求才称为成功。相信我,几年前我试过这个,你只是累了。使用图书馆。 FileUploader 不错。
    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多