如何在成功发布表单后不刷新页面且不使用Ajax的情况下更新页面内容

时间:2019-05-16 06:23:02

标签: razor asp.net-mvc-5

在cshtml文件中,有一个表单,我想更新数据而不刷新整个页面,仅刷新该表单。 After Updation of form user spam count form value image is here 我只是在表单标签中输入操作方法,输入标签值会在该方法上传递给控制器​​并更新该值,但整个页面都会刷新,但我只想刷新该表单。Befor Update any value

1 个答案:

答案 0 :(得分:0)

使用Ajax Post,您可以发布数据而无需刷新整个页面。

示例:

HTML

<h2>PostDataForm</h2>
<div class="card mb-3">
  <div class="card-header">
    <i class="fas fa-table"></i>
    Form 1
  </div>
 <div class="card-body">
    <div class="form-group">
            <input type="text" id="Email1" name="Email1" class="form-control" 
     placeholder="Email address" >
    </div>
    <input type="button" id="BtnForm1" class="btn btn-primary btn-block" 
   value="Submit" />
   </div>
 </div>
  <div class="card mb-3">
 <div class="card-header">
    <i class="fas fa-table"></i>
    Form 2
</div>
<div class="card-body">
    <div class="form-group">
        <div class="form-label-group">
            <input type="text" id="Email2" name="Email2" class="form-control" 
   placeholder="Email address" >
        </div>
    </div>
    <input type="button" id="BtnForm2" class="btn btn-primary btn-block" 
  value="Submit" />
  </div>
  </div>

 <div class="card mb-3">
<div class="card-header">
    <i class="fas fa-table"></i>
    Form 3
</div>
<div class="card-body">
    <div class="form-group">
        <div class="form-label-group">
            <input type="text" id="Email3" name="Email3" class="form-control" 
  placeholder="Email address">
        </div>
    </div>
    <input type="button" id="BtnForm3" class="btn btn-primary btn-block" 
  value="Submit" />
</div>
</div>

JS

<script src="/vendor/jquery/jquery.min.js"></script>
 <script type="text/javascript">

$(document).ready(function() {
    $("#BtnForm1").click(function () {
        if ($("#Email1").val() != '') {
            $.ajax({
                type: 'POST',
                url: '/User/PostDataForm1',
               // dataType: 'json',
                data: { email: $("#Email1").val() },
                success: function() {
                    alert("Form 1 submitted successfully!");
                },
                error: function (ex) {

                    alert("ex");
                }
            });
        } else {
            alert("Please Form 1 email address");
        }
    });
});

</script>

控制器

  public ActionResult PostDataForm() {
        return View();
    }

    [HttpPost]
    public ActionResult PostDataForm1(string email) {
        //update your data
        return Json("Success", JsonRequestBehavior.AllowGet);
    }

类似地将剩余表格写为方法