问题
How do you return to a named anchor in page when modelstate is not valid? This is probably a simple answer, but I can't seem to find the answer.
In most solutions using a named anchor, the MVC controller modelstate is lost and I want to return to the position of the form on the page with all of the model attributes intact. The code shown below DOES NOT WORK. I've tried a dozen different scenarios and I'm lost. Any help would be appreciated. It's probably something simple.
if (ModelState.IsValid)
{
...do something
}
else
{
return View("MyView#NamedAnchor")
}
回答1:
Another alternative that has been offered is to just abandon the named anchor altogether and design Views where the form is at the top of the page. This would eliminate the need for the steps I've shown above. But if anyone else has a better solution, please post it here.
回答2:
I discovered a workaround. It may not be elegant, but it works and most important it retains the model attributes that flow back into the View. It consists of three steps.
Since I have a site that uses a lot of forms with long pages, I can reuse this over and over. If I have two forms, then I can just modify the javascript and add a second div ID, or a third AND ViewBags to handle each form. The important part is to remember to initialize the value of ViewBag.FormOneTop in your controller and include the div in your view.
STEP 1:
Add a div to your VIEW above your BeginForm(). Name the id whatever you want.
<div id="FormOne"></div>
@using (Html.BeginForm())
STEP 2:
Add the following javascript below your JQuery link on your SHARED LAYOUT page, usually _Layout.cshtml or something like that. Change the name of FormOne to whatever you named the div. I used an offset of -75 because I have a responsive navbar at the top, you may not need an offset.
<script>
$(document).ready(function ()
{
var FormOneTop = '@ViewBag.FormOneTop';
if (FormOneTop== 'True')
{
$('html, body').animate(
{
scrollTop: $("#FormOne").offset().top -75
}, 1000);
}
});
</script>
Step 3:
Add code to the actions in your CONTROLLER that set the value of ViewBag.FormOneTop. I set it to "False" when loading the Index page without a form post and the page goes to the top. If I just "posted" the form action, I set the ViewBag.FormOneTop "True" if ModelState.IsValid fails.
public ActionResult Index()
{
ViewBag.FormOneTop= "False";
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "id,first_name,last_name,email")] MyTable MyTable)
{
if (ModelState.IsValid)
{
ViewBag.FormOneTop= "False";
return View();
}
else
{
ViewBag.FormOneTop= "True";
return View();
}
}
来源:https://stackoverflow.com/questions/41682322/how-to-return-to-a-named-anchor-in-page-when-modelstate-is-not-valid