【问题标题】:How to upload file from nested form & prevent client validation of master form in MVC 4?如何从嵌套表单上传文件并防止客户端验证 MVC 4 中的主表单?
【发布时间】:2014-01-31 22:41:12
【问题描述】:

当我单击嵌套表单提交按钮上传文件时,它会触发客户端验证,我想阻止这种情况。
我尝试过使用两个单独的表单元素,它可以工作。但我必须使用嵌套表单元素,因为这是要求(出于设计目的)。

下面是我的代码。

查看代码

    @using (Html.BeginForm("AddEdit", "Leads", FormMethod.Post, new { @Id = "frmSaveLead", @class = "form-horizontal" }))
     {
        @Html.TextBoxFor(model => model.stTitle, new { @class = "m-wrap span12",     @placeholder = "Lead Title", @maxlength = "100" })

        @Html.ValidationMessageFor(model => model.stTitle)

        @Html.TextAreaFor(model => model.stNote, new { @class = "m-wrap span12", @placeholder = "Lead Note" })

        @Html.ValidationMessageFor(model => model.stNote)

        @using (Html.BeginForm("FileUpload", "Leads", FormMethod.Post, new { @Id = "frmFileUpload", @enctype = "multipart/form-data" }))
        {

             <span class="btn green fileinput-button"><i class="icon-plus icon-white">              </i>
             <span>Add file...</span>
             <input type="file" name="files">
             </span>

             <button type="submit" class="btn blue start">
                     <i class="icon-upload icon-white"></i><span>Start upload</span>
             </button>
        }

        <button type="submit" class="btn blue">
            <i class="icon-ok"></i>Save
       </button>
    }

【问题讨论】:

  • “我必须使用嵌套表单元素,因为这是要求”这是一个可怕的要求,看看如何根据 HTML 规范不允许嵌套表单。
  • @Marek,是的,我知道,这不是正确的方法。但出于设计目的。
  • 您可以尝试使用 jquery 以 json 格式发送表单
  • @Nilesh,但是如何将 HttpPostedFileBase 对象发送到控制器的 ActionResult?

标签: asp.net-mvc forms validation file-upload


【解决方案1】:

你的内在形态

<form id="login-form">
    <input type="file" name="photo" id="files" accept="image/*;capture=camera">
    <button type="button" onclick="submitform()">Submit</button>
  </form>

jquery

function submitform(){
        var postdata = $('#login-form').serialize();          
        var file = document.getElementById('files').files[0];
        var fd = new FormData();
        fd.append("files", file);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/Home/Index", false);
        xhr.send(fd);    
    }

控制器

[HttpPost]
    public JsonResult Index(FormCollection data)
    {

      if (Request.Files["files"] != null)
        {
           HttpPostedFileBase file = Request.Files["files"];
        }
        return Json(something);
    }

【讨论】:

  • Imagefile 是否等同于 HttpPostedFileBase 类型?
  • 是的,它相当于 HttpPostedFileBase 的类型
  • 好的,我试试这个。回头见。谢谢。
  • 其实Request.Files["files"]等价于HttpPostedFileBase的对象。
  • 以及为什么我们需要追加,fd.append("files", file); ?请解释一下。
猜你喜欢
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 2011-02-08
  • 2011-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多