ValidationSummary not appearing with Partial Views

家住魔仙堡 提交于 2019-12-11 10:45:49

问题


I have this problem:

I go to a page such as:

/Auction/Details/37

and this calls this action method:

public ActionResult Details(int id)

A particular line in this method is:

return View("DetailsLub", auction);

This view contains this line:

@Html.Action("BidOnAuction", new { auctionId = Model.Id })

Which calls this action method:

public PartialViewResult BidOnAuction(int auctionId)

So far so good?

Now, I have a form in the BidOnAuction view, whcih has a button. When I click on this button, this action method is invloked:

[HttpPost]
public ActionResult BidOnAuction(BidOnAuctionViewModel model)

This action method has a catch statement with the following lines:

ModelState.AddModelError(string.Empty, operation + @" Failure: " + message);
return RedirectToAction("Details", new { id = model.AuctionId });

Now, both the DetailsLUB view and the BidOnAction view contain this line:

@Html.ValidationSummary(true)

But, the issue is that nothing ever gets printed to the screen. What am I doing wrong?


回答1:


This line of code

return RedirectToAction("Details", new { id = model.AuctionId });

Returns instance of RedirectResult class. That is generally used for redirections and does not render view. If you want to render child action into parent view using @Html.Action, you need to return view from that child action, not RedirectResult. And that RedirectResult will not work even when there's no child action. Returning RedirectResult causes browser to issue fresh, all new request to that action. And model state is lost anyways. You should do something like

try
{
    //some actions
    return RedirectResult("Details", new { id = model.AuctionId });
}
catch
{
    ModelState.AddModelError(string.Empty, operation + @" Failure: " + message);
    return View("Details", new { id = model.AuctionId });
}



回答2:


InOrder to get the validation Message on the page you need to return view with Model, as model has the Model State within it, something like this:

return View(Model);

This will return the model BidOnAuction with Validation Summary.




回答3:


You can't redirect to a new action and expect the modelstate to be there.

If the modelState is invalid just return (with View(model)) else redirect to details.

If you need the error information in the details view you will have add it to TempData or pass it in as an optional parameter.



来源:https://stackoverflow.com/questions/8986634/validationsummary-not-appearing-with-partial-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!