将值绑定到 Asp.Net MVC 应用程序中的模型

Bind value to model in Asp.Net MVC Application

本文关键字:应用程序 模型 MVC Net 绑定 Asp      更新时间:2023-09-26

在我的模型中,我有一个HttpPostedFileBase属性作为File。在视图中,我有一个文本框"A"和一个按钮"B"。我还有一个隐藏的输入类型="文件"id ="文件"在我的页面上。在 B 单击时,我会触发 #file.click,在我的 JavaScript 中。然后,所选文件应绑定到模型属性,并且文件名应显示在文本框中。我无法做到这一点。有什么帮助吗?我希望问题清楚,如果没有,请告诉我,以便我进一步详细说明。

有什么帮助吗?

编辑 1:

型:

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

视图:

<script type="text/javascript">
    $(document).ready(function () {
        $("#Browse").click(function () {
            $("#fileIputType").trigger('click');
           //now the file select dialog box opens up
          // The user selects a file
          // The file should get associated with the model property in this view
          // the textbox should be assigned the filename 
        });
    });
</script>

    @Html.TextBox("fileTextBox", Model.FileName, new { id = "fileTextBox" })
        <input type="button" id="Browse" name="Browse" value="Browse" />
        <input type="file" id="fileInputType" style="visibility:hidden"/> 
        @Html.Hidden("ModelType", Model.GetType())
  //How can i bind the selected file to the model property ( public HttpPostedFileBase File )

File分配给文件输入的 name 属性

    <input type="file" name="File" id="fileInputType" style="visibility:hidden"/> 
当您

提交表单时,这将绑定到操作方法中的HttpPostedFileBase file参数。

编辑:

窗体的entype设置为multipart/form-data

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new {enctype="multipart/form-data" })

您不能以编程方式在 javascript 中设置 input type='file' 元素value属性。

为什么不将文件名显示为标签文本?在模型(视图模型)类中具有FileName属性

@model MyViewModel
{
<label>@Model.FileName</label>
}

编辑:

基于您的代码

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

在视野中

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

在控制器中

    using (MemoryStream memoryStream = new MemoryStream())
    {
        model.File.InputStream.CopyTo(memoryStream);
    }