I'm having some problem with a checkbox in a view.
In my view I have this code:
<script>
function ShowRes()
{
if (document.getElementById("notres").style.display == "none") {
document.getElementById("notres").style.display = "block";
}
else
{
document.getElementById("notres").style.display = "none";
}
</script>
<div class="editor-label">
@Html.LabelFor(model => model.res)
</div>
<div class="editor-field" >
@Html.CheckBoxFor(model => model.res, new {onChange="javascript:ShowRes();"})
@Html.ValidationMessageFor(model => model.res)
</div>
<div id="notres">
<div class="editor-label">
@Html.LabelFor(model => model.resEmail)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.resEmail)
@Html.ValidationMessageFor(model => model.resEmail)
</div>
...and some other divs
</div>
Here I have a checkbox where onchange call a function that shows or hide a div (div id=notres)
My problem is that some other fields when not setted right throw an exception, see my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "...fields...")] Asset asset)
{
try
{
if (ModelState.IsValid)
{
if ("fields" == false)
{
throw new DataException();
}
else
{
db.Asset.Add(asset);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
}
When this exception is thrown the checkbox continues as it was. For example if it was checked it stay checked, if it was unchecked it stay unchucked. Buut my div always show again.
My intention was to make div unseen when the checkbox was checked, and seen when was unchecked, however the exception updates the page keeping the checkbox but reseting the div.
How can I make for when the exception updates the page the div respect the checkbox?
have already tried to set the box for always checked or unchecked like:
@Html.CheckBoxFor(model => model.res,
new {@checked = "checked", onChange="javascript:ShowRes();"})
but it only works for the first time, when exception occurs dont update it.