【问题标题】:Bind value to model in Asp.Net MVC Application在 Asp.Net MVC 应用程序中将值绑定到模型
【发布时间】:2013-11-19 00:07:44
【问题描述】:

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

有什么帮助吗?

编辑 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 )

【问题讨论】:

  • 如果您显示一些代码会有所帮助。
  • @WannaCSharp 我添加了一些代码...如果有帮助:)
  • 在你的脚本中,你有 $("#fileIputType") 但在你的 html 中你有 id="fileInputType"
  • @charlieparker 这样吗?它是一个 id...这就是我们访问它的方式,不是吗?
  • 我认为它显示在文本框中,但你看不到它,因为它隐藏了??

标签: c# javascript asp.net-mvc model-view-controller view


【解决方案1】:

将File 分配给文件输入的名称属性

    <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" })

【讨论】:

  • 您是否将表单的 enctype 设置为 multipart/form-data?检查我的编辑
  • 你有FileUploadModel作为你的参数还是只有HttpPostedFileBase?
  • 尝试接受HttpPostedFileBase作为你的参数,如果它可以工作的话。
  • hmm..将尝试...感谢您的耐心...顺便说一句,必须执行一项重要任务...会尽快回复您
【解决方案2】:

您不能以编程方式在 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);
    }    

【讨论】:

  • 我不想在 javascript 中设置 input type='file' 元素值属性。我只想在文本框中显示文件的名称。我想将输入类型=“文件”选择的文件绑定到模型属性
  • @kewal,因为在模型中具有 File 作为 FileStream 属性以及 TextBox 的 FileName 属性,并且两者都使用
  • 我无法绑定,当我在控制器中调试它时我得到 null
  • @kewal,检查如何将File元素与模型绑定
  • 我试过...找不到任何具体的东西...你能指出正确的方向吗
猜你喜欢
  • 1970-01-01
  • 2011-03-03
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
相关资源
最近更新 更多