回发后{J}动作更改

时间:2015-10-12 16:50:09

标签: javascript jquery asp.net checkbox

我有一个Javascript,当选中TrainingRequired复选框以显示两个提交按钮时触发。取消选中后,会显示一个提交按钮。问题是当我选中复选框并尝试在一个必填字段中提交没有数据的表单时,会通过回发返回错误消息。复选框保持选中状态,两个按钮不再显示。如何在回发后使用错误消息保持两个按钮可见?

HTML标记:

<tr>
    <td>
        <label for="trainingRequired">
            Training Required?*</label>
    </td>
    <td>
            @Html.CheckBox("trainingRequired", Page.TrainingRequired, new { id = "chkImmediate" })
    </td>
</tr>
<tr id="allowSelfTrainingBlock">
    <td>
        <label for="allowSelfTraining">
            Allow Self Training?</label>
    </td>
    <td>
                @Html.CheckBox("allowSelfTraining", Page.AllowSelfTraining)
    </td>
</tr>

RegularButton和RequiredButton阻止:

<div id="RegularButton">
<input name="btn" type="submit" id="notrequired" value="Save" />
<a href="@Page.ReturnUrl" id="notrequiredurl">Cancel</a>
</div>

<div id="RequiredButton">Create New Training Document?<br />
<input name="yesbtn" type ="submit" id="required" value="Yes" />
<input name="nobtn" type="submit" id="required2" value="No & Save" />
<a href="@Page.ReturnUrl" id="requiredurl">Cancel</a>
</div>

同一页面上的Javascript:

<script type="text/javascript">

function prepareButtons() {
    document.getElementById("RequiredButton").style.display = "none";
    document.getElementById("RegularButton").style.display = "block";
}

//**********PostBack*************
function postBack(val) {
    $('#xtravar').val(val);
    $('form').submit();
}
$("#chkImmediate").change(function() {
    if(this.checked) {
        document.getElementById('allowSelfTrainingBlock').style.visibility = 'visible';
        document.getElementById("RequiredButton").style.display = "block";
        document.getElementById("RegularButton").style.display = "none";
    }
    else {
        document.getElementById('allowSelfTrainingBlock').style.visibility = 'hidden';
        document.getElementById("RequiredButton").style.display = "none";
        document.getElementById("RegularButton").style.display = "block";
    }
});
window.onload = function () {
    prepareButtons();
}

回发后显示错误消息,我可以显示两个按钮,如果我取消选中并选中TrainingRequired复选框。但我真的希望在回发后显示两个按钮并显示错误消息。感谢。

1 个答案:

答案 0 :(得分:0)

由于在回发后会重新绘制页面,因此会再次调用window.onload。因此,您需要设置条件以检查是否发生错误。由于您使用MVC,您可以在控制器中创建ViewBag道具并在发生错误时进行设置。如下所示。

在控制器中,

public ActionResult Validate()
{
  if(Error)
  ViewBag.isError = true;
  return View();
}

在Js,

window.onload = function () {
    var error = '@ ViewBag.isError';
    if(error != 'true')
     prepareButtons();
}