2010-12-10 70 views
0
接收到的服务器成功消息下面

代码准备好测试:MVC3停止页面一旦从控制器

问题是,当启用e.preventDefault();而不是由ValidationMessageFor生成的每个控件的前面出现的单个错误,并在e.preventDefault()时显示 。已启用。所有的错误都工作正常,但一旦代码处理,并成功返回的消息从 服务器端使整个网页提交/刷新:(

问:我如何阻止整个页面刷新自/回传如果E。的preventDefault();是启用和从服务器获得成功消息

<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> 

回答