Bind value to model in Asp.Net MVC Application Par

2019-06-06 02:08发布

问题:

This is sort of a follow up to Bind value to model in Asp.Net MVC Application.

I have a Model with different control classes. The relevant code:

public class FileUploadModel
    {
        public HttpPostedFileBase File { get; set; }
    }

I have a partial view with the following relevant code:

@Html.TextBoxFor(x => x.File, new { type = "file", id = "File", name = "File" }) 

Then there is a main view in which the partial view is rendered with the following relevant code:

@using (Ajax.BeginForm("ActionMethods", "Index", new AjaxOptions { UpdateTargetId = "parameterList" }, new { enctype = "multipart/form-data" }))
{

  <div id="parameterList">
        <div id="verifyBtnDiv" style="display:none;">

             **THIS IS WHERE THE PARTIAL VIEW AS SHOWN ABOVE WOULD BE RENDERED**

            <input type="submit" id="verifyBtn" value="Verify"/>

        </div>
 </div>

}

Now when the submit happens, the file does not binds to the model property. The control passes to the controller but i debug and see that its null. ANy suggestions regarding this?

回答1:

There are a few issues with the code you posted that will prevent what you are attempting to do from working.

First, I am pretty certain that you cannot use the @Html.TextBoxFor helper and convert it to a file input. If it works now, I would not rely on it as you are overriding what it is meant to put out and might break in the future. Let's just put out a file input with an Id and Name matching your ViewModel property.

<input type="file" name="File" Id="File/>

Next, you cannot use Ajax.BeginForm() to upload files. It is a limitation of AJAX, not an issue with the Ajax.BeginForm. So, we will need to update your form element to a normal, Html.BeginForm, with the proper enctype (this is important)

@using (Html.BeginForm("Upload", "MyControllerName", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
    <div id="parameterList">
        <div id="verifyBtnDiv" style="display:none;">
            <!-- Chose to just put the one line here instead of calling a partial-->
            <input type="file" name="File" Id="File/>
            <input type="submit" id="verifyBtn" value="Verify"/>
        </div>
 </div>
}

Lastly, if you have to/required to upload the file via AJAX, there are plenty of good recommendations on libraries to use for Ajax file uploads. I personally like the jQuery.Form plugin as it is pretty transparent in the way it handles file uploads.