首页 > 解决方案 > 仅在文件已上传时显示字段

问题描述

我有一个表格,如果我愿意,我可以在其中上传文件:

<div class="form-group">
   @Html.Label("Upload File", new { @class = "control-label col-md-2" })
   <div class="col-md-10">
      <input type="file" id="UploadedFile" name="upload" />
   </div>
</div>

我希望在上传文件时显示这些字段:

<div id="optionalFields">

    <div class="form-group">
       @Html.LabelFor(model => model.Field1, htmlAttributes: new { @class = "control-label col-md-2" })
       <div class="col-md-10">
           @Html.EditorFor(model => model.Field1, new { htmlAttributes = new { @class = "form-control" } })
           @Html.ValidationMessageFor(model => model.Field1, "", new { @class = "text-danger" })
       </div>
     </div>

    //other fields
</div>

我认为需要 Javascript,但我不知道如何实现这一点。

标签: javascripthtmlasp.net-mvcrazor

解决方案


要显示可选字段:

//hide the optional fields on page load
document.getElementById("optionalFields").style.display = 'none';
//when the file upload input is clicked, show the optional fields
document.getElementById('UploadedFile').onclick=function(){
  document.getElementById('optionalFields').style.display='block';
};

注意:以上代码是一个简单的演示,演示了点击文件上传输入时如何显示可选字段。它不包括用户实际选择要上传的文件的任何类型的验证。它也不包含文件上传成功的验证。


推荐阅读