@html.File For Returns Null MVC 4

时间:2013-12-02 02:38:39

标签: c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

尝试使用mvc4上传文件,并在我的控制器中返回im以获取文件上传。谁能明白为什么好吗?

查看模型

public class PostExtendedWithImage
{
    public Post post { get; set; }

    public HttpPostedFileBase file { get; set; }
}

查看

@using (Ajax.BeginForm("CreatePost", "Wall", new AjaxOptions
{
    HttpMethod = "post",
    InsertionMode = System.Web.Mvc.Ajax.InsertionMode.InsertBefore,
    UpdateTargetId = "newPost"}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)  


    <fieldset>
        <legend>Post</legend>

        <div class="editor-label">

        </div>
        <div class="editor-field">
            @Html.HiddenFor(model => model.post.Username, new { Value = User.Identity.Name })

        </div>

        @Html.FileFor(model => model.file)


            <div class="editor-label">
                @Html.LabelFor(model => model.post.PostContent)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.post.PostContent)
                @Html.ValidationMessageFor(model => model.post.PostContent)
            </div>

            @{
    TempData["returnURL"] = Request.Url.AbsoluteUri;
            }
            <p>
                <input type="submit" id="postStatus" value="Create" />
            </p>
</fieldset>
}

控制器

 [HttpPost]
        [ValidateAntiForgeryToken]
        public PartialViewResult CreatePost(PostExtendedWithImage VM)
        {

            if (ModelState.IsValid)
            {
                if (VM.file == null)
                {
                   // Do stuff     

                }

                else
                {
                    //Save file to DB
                }


                return PartialView("_NewStatusPartial",VM);

            }

            return PartialView("All",VM);
        }

2 个答案:

答案 0 :(得分:1)

使用Ajax.BeginForm提交异步文件可能无法实现。您可以使用第三方插件来执行此ajax提交。

您可以在此上下文中使用jQuery Forms PluginSee你怎么能this使用这个插件。

// bind to the form's submit event 
    $('#myForm2').submit(function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        $(this).ajaxSubmit(options); 

        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    }); 

这么简单。试一试!

答案 1 :(得分:0)

我不太熟悉Ajax.BeginForm,但是,如果您要上传文件,则通常需要将enctype="multipart/form-data"添加到<form>标记。

不确定这是否适用于AJAX。

相关问题