How to create MVC 4 @Html.TextBox type=“file”?

后端 未结 7 2144
萌比男神i
萌比男神i 2021-02-20 14:57

I need to add the following field at my form


I create model and describe this field (the las

相关标签:
7条回答
  • 2021-02-20 15:06
      @using (Html.BeginForm("Action_Name", "Controller_Name",FormMethod.Post))
       {
            @Html.TextBoxFor(m => m.Email, new {@class = "text_field"})
            @Html.ValidationMessageFor(m => m.Email)
       }
    
    0 讨论(0)
  • 2021-02-20 15:06

    You can use the below syntax

    @Html.TextBoxFor(model=>model.Email, new { @type="file", @class="input-file" })
    
    0 讨论(0)
  • 2021-02-20 15:15

    I solved this problem using enctype="multipart/form-data"

    @using (Html.BeginForm("SalvarEvidencia", "Evidencia", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        ...
    }
    
    0 讨论(0)
  • 2021-02-20 15:21

    Model

    public class FeedbackForm
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Company { get; set; }
        public string AdditionalInformation { get; set; }
        public HttpPostedFileBase ProjectInformation { get; set; }
    }
    

    View

    @model FeedbackForm
    
    @Html.TextBox("Name")
    @Html.TextBox("Email")
    ...
    @Html.TextBox("ProjectInformation", null, new { type="file", @class="input-file" })
    
    // submit button
    

    My recommended view (strongly - typed)

    @model FeedbackForm
    
    @Html.TextBoxFor(model=>model.Name)
    @Html.TextBoxFor(model=>model.Email)
    ...
    @Html.TextBoxFor(model=>model.ProjectInformation, null, new { type="file", @class="input-file" })
    
    // submit button
    

    Controller

    [HttpPost]
    public ActionResult FeedbackForm(FeedbackForm model)
    {
        // this is your uploaded file
        var file = model.ProjectInformation;
        ...
    
        return View();
    }
    

    MVC is using name convention, so if your textbox and model names match, then MVC will bind your inputs to your model.

    0 讨论(0)
  • 2021-02-20 15:24

    You need to specify the name of the field. If you don't want a name, nor a value, it's better to just include the field as is in your form.

    It doesn't make sense to use a helper, if there's nothing dynamic about it.

    0 讨论(0)
  • 2021-02-20 15:26

    There's nothing wrong with just using the input tag directly in your view. You aren't required to use a helper.

    <input type="file" class="input-file" />
    

    Just make sure it's within your BeginForm declaration block.

    0 讨论(0)
提交回复
热议问题