在mvc 2中上传控件 [英] Upload control in mvc 2
问题描述
大家好,我是mvc的新手...目前我正在处理文件上传,应该使用适当的验证进行处理。最重要的是文件大小验证。我开始知道用javascript无法完成...所以我的代码是这样的。
Hi all , i am new to mvc ... currently i am working on a file uploading which should be processed with proper validations . The most important is the file size validation . i came to know that it cannot be done using javascript ... So my code goes like this .
[HttpPost]
public ActionResult FileUpload(IEnumerable<HttpPostedFileBase> UploadedFile)
{
try
{
List<string> uploaderror = new List<string>();
int cnt = 1;
foreach (var item in UploadedFile)
{
if (item != null)
{
if (item.ContentLength > 1048576)
{
string test = "lbl_error" + cnt;
uploaderror.Add(test);
cnt++;
}
}
}
ViewData["UploadError"] = uploaderror;
//var filename = Path.GetFileName(uploadFile.FileName);
//var filesize = uploadFile.ContentLength;
}
catch (Exception ex)
{
}
return View();
}
我的观点是
And my View is
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="Upload_Div">
<%Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype="multipart/form-data" }); %>
<ul>
<li>
<input type="file" id="File" name="UploadedFile"/> <label name="lbl_error1" id="Label"></label></li>
<br />
<li><input type="file" id="File1" name="UploadedFile"/> <label name="lbl_error2" id="Label1"></label></li>
<br />
<li><input type="file" id="File2" name="UploadedFile"/> <label name="lbl_error3" id="Label2"></label></li>
<br />
<li><input type="file" id="File3" name="UploadedFile"/> <label name="lbl_error4" id="Label3"></label></li>
<br />
<li><input type="submit" />
</li>
<li></li>
</ul>
</div>
我的问题是我将如何返回相同的视图以及如何使用viewdata [UploadError]显示文件大于1 mb的相应上传控件旁边的错误消息。
提前谢谢:)
My problem is how will i return to the same view and how will i use the viewdata["UploadError"] to show error message adjacent to repective upload control having file greater than 1 mb .
Thanks in advance :)
推荐答案
一个解决方案是在actionResult中将上传错误设置为viewdata时设置fileUploadControl id也附加此字符串。例如
YourFile对于viewdata来说是1 mb:FileUpload id。。使用javascript或jquery返回视图后,取下面的viewdata值
One Solution is when setting the upload error to the viewdata in the actionResult set fileUploadControl id also append with this string. for example
YourFile is more 1 mb:FileUpload id. to the viewdata. After returning the view by using javascript or jquery take the viewdata value like below
function YouJsFunction(){
var test = '@ViewData["UploadError"].ToString()';
//Split error and file upload id
}
之后通过使用jquery或javascript设置错误消息来创建div,并将潜水附加到我们得到的特定文件上载控件。
希望这有助于
After that create div by setting the error message using jquery or javascript and append the dive to the particular fileupload control we got.
Hope this helps
这篇关于在mvc 2中上传控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!