使用Html.BeginForm和ajax调用相同的动作有冲突吗?

问题描述

当我尝试添加Ajax并将其他数据传递到动作控制器时,我的模型参数受到影响,该值为null,而我的Ajax参数具有一个值。
我不认为这是因为我使用的是Html.beginform('index','payable'),而我使用的是Ajax url: '@Url.Action("index","payable")',和相同的ActionResult.

您可以在下面看到参考。

@using (Html.BeginForm("index","payable",FormMethod.Post,new { enctype = "multipart/form-data" }))<div class="col-md-2">
        <div class="form-group">
            @Html.LabelFor(x => x.Amount,new { @class = "form-label" })
            @Html.TextBoxFor(x => x.Amount,new { @class = "form-control" })
        </div>
    </div>

    <div class="col-md-2">
        <div class="form-group">
            @Html.LabelFor(x => x.ImagePath,new { @class = "form-label" })
            <input type="file" name="file" id="files" />
        </div>
    </div>

    <div class="col-md-2">
        <div class="form-group">
            <button type="submit" id="btnUpload" class="btn btn-primary btn-sm" onclick="saveSelected()"><i class="fas fa-save"></i> &nbsp;Submit Payment</button>
        </div>
    </div>{

我的Ajax

function saveSelected() {

        $.ajax({
            url: '@Url.Action("index",type: 'POST',data: { ids: ids },Traditional: true,success: function (data) {
                alert("success");
            }
        });
     }

我的控制器

 public ActionResult Index(PayableFormModel model,HttpPostedFileBase file,int[] ids) 
    {
        return View();
    }

解决方法

  • HTML。Beginform和ajax不能同时使用,即使您添加了 onclick功能。因此,ajax将无法正常工作,并且所有数据均已提交 通过形式。如果要提交模型和任何其他数据,请将它们全部放入表单或仅使用ajax。

  • 上载文件时,模型无法直接获取文件的名称或路径。您应该将文件存储到文件夹或目录中,然后将此路径分配给模型的图像路径。(示例代码为自爆)

  • 在索引页面中,{}应该跟随using(),否则将报告错误。

     public ActionResult Index(PayableFormModel model,HttpPostedFileBase file,int[] ids)
     {
         string filepath = Server.MapPath("~/image/");
         Directory.CreateDirectory(filepath);
         file.SaveAs(Path.Combine(filepath,file.FileName));
         model.ImagePath = filepath + file.FileName ;
    
         return View();
     }