所以我试图弄清楚如何更新cshtml文件中的特定元素,例如标签。
因此标签目前是<p>File ready for upload</p>
,当我点击按钮时,我希望它更改为<p>Files must be a <b>.jpeg</b> <b>.jpg</b> <b>.png</b> <b>.bmp</b> file format.</p>
我已经有逻辑工作上传并且只允许这些文件格式,我只想通过更改我上面说过的标签来提醒用户他们需要它。我知道它会在catch (exception)
中,因为我使用的是try catch
语句。
我的代码: 控制器: FileSharings.cs
public ActionResult Create([Bind(Include = "Id,Title,Description,FileName,FileType,FileSize,Author,DateUploaded")] FileSharing fileSharing)
{
HttpPostedFileBase file = Request.Files.Get(0);
string fileName = Path.GetFileName(file.FileName);
string filePath = Path.Combine(Server.MapPath("~/Assets/"), fileName);
var allowedExtensions = new string[] { ".jpeg", ".png", ".jpg", ".bmp" };
string fileExtension = Path.GetExtension(file.FileName).ToLower();
string extension = Path.GetExtension(file.FileName);
try
{
if (Request.Files.Count > 0 && (ModelState.IsValid) && (allowedExtensions.Contains(extension)))
{
file.SaveAs(filePath);
FileInfo fileInfo = new FileInfo(filePath);
fileSharing.FileType = fileInfo.Extension.Remove(0, 1).ToLower();
fileSharing.DateUploaded = DateTime.Now;
fileSharing.FileName = fileName;
fileSharing.FileSize = fileInfo.Length.ToString();
fileSharing.Author = User.Identity.Name;
db.FileSharing.Add(fileSharing);
db.SaveChanges();
}
}
catch (Exception)
{
}
return View(fileSharing);
}
答案 0 :(得分:0)
#
public ActionResult Index()
{
ViewBag.MyMessageToUsers = "Files must be a <b>.jpeg</b> <b>.jpg</b> <b>.png</b> <b>.bmp</b> file format";;
return View();
}
CSHTML.cs
@ViewBag.MyMessageToUsers
答案 1 :(得分:0)
JQuery解决方案
// get file name
var filename = $("#file_input").val();
// get extension
var ext = filename.replace(/^.*\./, '');
// Validate
if($.inArray( ext, [ ".jpeg", ".png", ".jpg", ".bmp" ] ) == -1)
$("#label_error").html("file extension not matched");