I am building a WebPages site and have an issue when I try to pass ModelState
data to a partial page.
Here is the code for Create.cshtml:
@{
Page.Title = "Create Fund";
var name = "";
if (IsPost) {
name = Request.Form["name"];
if (!name.IsValidStringLength(2, 128)) {
ModelState.AddError("name", "Name must be between 2 and 128 characters long.");
}
}
}
@RenderPage("_fundForm.cshtml", name)
Here is 开发者_JAVA百科the code for _fundForm.cshtml:
@{
string name = PageData[0];
}
<form method="post" action="" id="subForm">
<fieldset>
@Html.ValidationSummary(true)
<legend>Fund</legend>
<p>
@Html.Label("Name:", "name")
@Html.TextBox("name", name)
@Html.ValidationMessage("name", new { @class = "validation-error" })
</p>
<p>
<input type="submit" name="submit" value="Save" />
</p>
</fieldset>
</form>
The issue I am having is when there is an error for "name", the validation error does not display. Is there a special way to pass ModelState
between the two pages?
_fundForm
is going to be shared between Create.cshtml and Edit.cshtml.
ModelState is a readonly property of System.Web.WebPages.WebPage class. Its backing field is a private ModelStateDictionary and is initialized at first access. I can't see any way to force ModelState across pages, apart from doing it via reflection as seen in SO question: Can I change a private readonly field in C# using reflection?
Otherwise, you can simply use a third parameter in the invocation, like this:
@RenderPage("_fundForm.cshtml", name, ModelState);
In effect, the first parameter after the page name will become the Model of the new page, so there is enough space (i.e. the next parameter) to pass the ModelState.
In your "_fundForm.cshtml" merge the ModelState received by the calling page with the local one, like this:
@{
//In _fundForm.cshtml
var ms = PageData[1];
ModelState.Merge((ModelStateDictionary)ms);
}
精彩评论