views:

391

answers:

1

I have a file upload function in my asp.net mvc application that allows users to upload an xslx file containing data that should be persisted to a database. That data can be related to one of many categories. I need to be able to discern which category the data that is coming in is supposed to be related to, so I thought that a drop down list would be perfect for the job. However, I don't know how to get at the lists selected value when the user posts the data. This is what the code for the form looks like:

    <form action="/Import/UploadFiles/" method="post" enctype="multipart/form-data">
    <fieldset id="fileImport">
        <legend>Importinställningar</legend>
        <label for="file">Importfil:</label>
        <input type="file" id="file" name="file" />
        <%= Html.DropDownList("Name", (IEnumerable<SelectListItem>)ViewData["assignments"]) %>
        <p>
            <input type="submit" value="Spara"/>
            <input type="button" value="Avbryt" onclick="window.location.href='/'" />
        </p>
    </fieldset>
</form>

Since I am dealing with a file upload scenario I don't have an action link that I can use to pass data to the controller, but rather an input with the type submit.

How should I go about reading the select value of the drop down list so that its selected value can be passed to the Controller?

A: 

There are a couple of different ways that you can make this work. First, add a string parameter named Name to your UploadFiles method. The default binder will fill it in from the form value with the same name. Alternatively, you can use the ValueProvider inside the controller -- if you use the same action for both rendering the view and responding to the post, for instance -- to extract the value of the parameter named Name.

public ActionResult UploadFiles( string Name )
{
    ...
}

or

public ActionResult UploadFiles()
{
     string name = this.ValueProvider.ContainsKey("Name")
                         ? this.ValueProvider[key].AttemptedValue
                         : null;

     ...
 }
tvanfosson
I got stuck thinking I had to pass the value through the resulting Url. Of course this works. Thanks a bunch! Takes a little while to get used to MVC :)
Ciddan