[英]Bind value to model in Asp.Net MVC Application
在我的模型中,我有一個HttpPostedFileBase屬性作為File。 在視圖中,我有一個文本框“ A”和一個按鈕“ B”。 我的頁面上還有一個隱藏的輸入type =“ file” id =“ file”。 在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'
file'elements value
屬性。
為什么不將文件名顯示為標簽文本? 在模型(viewmodel)類中具有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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.