从控制器收到服务器成功消息后,停止刷新页面

时间:2010-12-10 05:16:30

标签: jquery asp.net-mvc-3

以下代码已准备好测试:MVC3

问题是当我启用e.preventDefault();而不是单个错误没有弹出ValidationMessageFor生成并显示的每个控件的前面 当e.preventDefault();已启用。所有错误都正常工作,但一旦代码处理完毕,成功的消息返回 从服务器端使整个页面POSTBACK / REFRESH :(。

问题: 如果e.preventDefault();我如何从刷新/回发中停止整个页面是否启用并从服务器获取SUCCESS消息?

<script type="text/javascript">
  $(function () {
      $("#personCreate").click(function (e) {
          //e.preventDefault(); -------> Here is the problem

          var profile = {
                 FirstName: $("#FirstName").val(),
                 LastName: $("#LastName").val()
             };


          $.ajax({
              url: '/Test/save',
              type: 'POST',
              dataType: 'json',
              data: JSON.stringify(profile),
              contentType: 'application/json; charset=utf-8',

              //beforeSend: function () { $("#saveStatus").html("Saving").show(); },
              //complete: function () { $("#saveStatus").html("Saving").hide(); },
              success: function (data) {
                  // get the result and do some magic with it
                  var message = data.Message;
                  $("#resultMessage").html(message);
              }
          });
      });
  });

</script>

//控制器代码

[HttpPost]
public ActionResult Save(CreateViewModel userVm)
{
    if (ModelState.IsValid)
    {
        return Json(new CreateViewModel { Message = "Passed" });
    }
    else
    {
        return Json(new CreateViewModel { Message = "Failed" });
    }
}

// Create.cshtml

<span id="saveStatus"></span>

@using(Html.BeginForm())
{


        <fieldset>
        <legend>Contact Information</legend>
        <div>
            <table class="form-spacing">                        
                <tr>
                    <td class="cell-one">* @Html.LabelFor(model => model.FirstName) :</td>
                    <td class="cell-two">@Html.TextBoxFor(model => model.FirstName, new { @class = "big-field", tabindex = "1" })</td>
                    <td class="cell-three" >@Html.ValidationMessageFor(model => model.FirstName)</td>           
                </tr>
                <tr>
                    <td class="cell-one">* @Html.LabelFor(model => model.LastName) :</td>
                    <td class="cell-two">@Html.TextBoxFor(model => model.LastName, new { @class = "big-field", tabindex = "2" })</td>
                    <td class="cell-three" >@Html.ValidationMessageFor(model => model.LastName)</td>            
                </tr>
            </table>
         </div>
    </fieldset>

     <p>
        <input type="submit" value="Save" id="personCreate" />
    </p>

}

    <div>
        <span id="resultMessage"></span>
    </div>

1 个答案:

答案 0 :(得分:0)

请参阅此

http://iridescence.no/post/ASPNET-MVC-ActionResult-for-Rendering-JSON-using-JSONNET.aspx

在您的控制器中,您将返回ActionResult