Ajax调用取代了整个内容

时间:2013-06-12 08:37:32

标签: jquery asp.net-mvc-4 asp.net-ajax

我有一个表单和提交按钮。通常,当采取提交操作时,它将返回到新页面而不更新部分视图。我在jquery live函数中使用ajax调用,但它仍然替换整个内容而不是返回带有提供的模型的局部视图。以下是我在_detailfile.cshtml中的代码。应用程序上传文件但替换整个内容。

<div id="trainingFileDiv" style="overflow: auto; height: 470px;">
 <table class="fileTable">
                @foreach (var training in Model.TrainingList)
                {
                    using (Html.BeginForm("fileForm", "Home/TempUpload", new { employeeId = Model.Id, trainId= @training.Id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
                    {
                        if (training.TrainingFile != null)
                        {
                    <tr>
                        <td>
                        </td>
                    </tr>
                        }

                        else
                        {
                    <tr>
                        <td class="view_detail_label" style="width: 250px;">
                            @training.Name.Name
                        </td>
                        <td>
                            <input  type="file" name="@training.Id"/>
                        </td>

                    </tr>

                     <tr><td><input type="submit" name="Submit" id="Submit" value="Yükle" /></td>

                     </tr>
                        }

                    }

                }
            </table>
</div>

以下是我的脚本只更新div文件,但它不起作用。

 $("fileForm").live("submit",  function (event) {


         if (form.valid()) {
             $.ajax({
                 url: this.action,
                 type: this.method,
                 data: $(this).serialize(),
                 success: function (result) {
                     $('#trainingFileDiv').html(result);
                 }
             });
         }

         event.preventDefault();
     });

这是我在网上找到的另一个代码,它不会更新div而是更新所有内容。

$(function () {
    $('fileForm').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $('#trainingFileDiv').html(result);
                }
            });
        }
        return false;
    });
});

我在这里缺少什么? 谢谢你的帮助

EDIT1 当从控制器返回局部视图时,我得到Uncaught ReferenceError: $ is not defined fileForm:7

EDIT2 函数可以对所有表单进行ajaxify。我在edit1

中收到错误
  $(function () {
         $('form').submit(function () {
             if ($(this).valid()) {
                 $.ajax({
                     url: this.action,
                     type: this.method,
                     data: $(this).serialize(),
                     success: function (result) {
                         $('#trainingFileDiv').append(result);
                     },
                 });//end of ajax call
             }//end of if

         });     });

EDIT3 在下面的代码中,我没有错误,但Request中没有任何文件。您可以在函数下方看到控制器代码。但是当我返回true或false时,文件被放在Request对象中并发送到控制器。但它取代了我在返回时的所有内容。这有什么不对?

$('form').submit(function (event) {

         if ($(this).valid()) {
             $.ajax({
                 url: this.action,
                 type: this.method,
                 data: $(this).serialize(),
                 success: function (result) {
                     $('#trainingFileDiv').html(result);
                 },
                 complete: function () {
                     console.log("Complete");
                 },
                 error: function () {
                     console.log("Error");
                 }
             }); //end of ajax call
         } //end of if
         //return true;//if commented no error on jquery side but no files are passed to controlller
     });

  foreach (string upload in Request.Files)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
                string filename = Path.GetFileName(Request.Files[upload].FileName);
                TrainingFile file = new TrainingFile();
                file.Name = filename;
                file.Path = path;



                var training = _work.TrainingRepository.GetSet().Where(a => a.EmployeeId == employeeId && a.Id == trainId).ToList().ElementAt(0);
                training.TrainingFile = file;
                training.FileId = file.Id;

                _work.TrainingFileRepository.Add(file);
                _work.TrainingFileRepository.Save();
                _work.TrainingRepository.UpdateAndSave(training);
                _work.TrainingRepository.Save();

                Request.Files[upload].SaveAs(Path.Combine(path, filename));
            }

3 个答案:

答案 0 :(得分:1)

$('#trainingFileDiv').html(result);// ovverides already existing html

$('#trainingFileDiv').append(result); //adds new result to existing html

答案 1 :(得分:0)

您的选择器错误,并且不返回任何元素:

$('fileForm')

当然,您将提交处理程序附加到无元素。

您可能想使用id选择器来检索表单:

$('#fileForm')

另外,请不要忘记将此id分配给您的表单:

using (Html.BeginForm("fileForm", "Home/TempUpload", new { employeeId = Model.Id, trainId= @training.Id }, FormMethod.Post, new { enctype = "multipart/form-data", id = "fileForm" }))

或者如果您想要在页面上AJAXify所有表单(或者您只有一个表单),您可以使用:

$('form')

当然,完全相同的注释代表您的$("fileForm").live选择器。另请注意,.live方法很久以前就已弃用,除非您使用史前史的jQuery版本,否则您可能希望使用推荐的.on()函数。

答案 2 :(得分:0)

不幸的是,我还没有足够高的评论来发表评论,尽管我试图到达那里。 要获取表单,如果页面上只有一个表单,则可以使用$('表单')。 否则,依赖于您正在使用的视图引擎,您可能需要添加一些其他语法来指定表单的ID。

像Darin Dimitrov建议的那样:

using (Html.BeginForm("fileForm", "Home/TempUpload", new { employeeId = Model.Id, trainId= @training.Id }, FormMethod.Post, new { enctype = "multipart/form-data", id = "fileForm" }))
在Razor中你需要将@添加到id,这样就可以了:

@using (Html.BeginForm("fileForm", "Home/TempUpload", 
new { employeeId = Model.Id, trainId= @training.Id }, FormMethod.Post, 
new { enctype = "multipart/form-data", @id = "fileForm" }))