В моей программе MVC, после того как пользователь отправил форму редактирования, эти значения для объекта сохраняются на стороне сервера модели, но предыдущие значения отображаются в представлении.
Я знаю, что это связано с процессом валидации MVC, когда он сначала проверяет ModelState перед значениями на стороне сервера.Решение, которое я прочитал на форумах, - очистить ModelState.Единственная проблема, ModelState.Clear не работает для меня.
Помогите пожалуйста.
Модель
public class Help
{
[HiddenInput(DisplayValue=true)]
public int HelpID { get; set; }
[Required(ErrorMessage = "Please enter a proper URL")]
public string URL { get; set; }
[Required(ErrorMessage = "Please enter a content description:")]
[DataType(DataType.MultilineText)]
public string HelpContent { get; set; }
/*? 2 properites are nullable*/
public DateTime? createDateTime { get; set; }
public DateTime? modifiedDateTime { get; set; }
}
Контроллер
/*Create the admin controller*/
public class AdminController : Controller
{
//declare interface object
private IHelpRepository repository;
/*Pass a db interface to controller*/
public AdminController(IHelpRepository repo)
{
repository = repo;
}
/*default admin screen. displays help table obs*/
public ViewResult Index()
{
return View();
}
/*Returns add view form*/
public ActionResult AddForm()
{
return PartialView();
}
/*Will handle the post for the add screen after user has
submitted add information*/
[HttpPost]
[ValidateInput(false)] //this allows admin to place html in field
public ActionResult AddForm(Help help)
{
if (ModelState.IsValid) //if all fields are validated
{
//set the edit date
help.createDateTime = DateTime.Now;
repository.SaveHelp(help);
return (null); //return "null" to div so control is given back to main view
}
else //there is something wrong. send back to view
{
return PartialView(help);
}
}
/*Returns edit view form, searches for object to edit with id
if no id provided, 0 by default*/
public ActionResult EditForm(int helpID = 0)
{
Help help = repository.Help.FirstOrDefault(q => q.HelpID == helpID);
help.HelpContent = System.Web.HttpUtility.HtmlDecode(help.HelpContent);
return PartialView(help);
}
/*Will handle the post for the edit screen after user has
submitted edit information*/
[HttpPost]
[ValidateInput(false)] //this allows admin to place html in field
public ActionResult EditForm(Help help)
{
if (ModelState.IsValid) //if all fields are validated
{
//set the edit date
help.modifiedDateTime = DateTime.Now;
repository.SaveHelp(help);
ModelState.Clear();
return (null); //return "null" to div so control is given back to main view
}
else //there is something wrong. send back to view
{
return PartialView(help);
}
}
/*Delete action method, searches with id*/
[HttpPost]
public ActionResult Delete(int helpId)
{
Help helpDel = repository.Help.FirstOrDefault(p => p.HelpID == helpId);
if (helpDel != null) //if the object is found, delete
{
repository.DeleteHelp(helpDel);
}
//in all cases return to index
return RedirectToAction("Index");
}
/*Used by the telerik table to rebind grid*/
[GridAction]
public ActionResult AjaxBinding()
{
return View(new GridModel(repository.Help));
}
}//end admin controller class`
Частичное представление (загружается в div) `
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "Editx" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Edit Entry</legend>
@Html.HiddenFor(model => model.HelpID)
<div class="editor-label">
@Html.LabelFor(model => model.URL)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.URL)
@Html.ValidationMessageFor(model => model.URL)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.HelpContent, "Help Content")
</div>
<div class="editor-field">
@{
Html.Telerik().EditorFor(content => content.HelpContent)
.Name("HelpContent")
.FileBrowser(settings => settings
.Browse("Browse", "ImageBrowser")
.Thumbnail("Thumbnail", "ImageBrowser")
.Upload("Upload", "ImageBrowser")
.DeleteFile("DeleteFile", "ImageBrowser")
.DeleteDirectory("DeleteDirectory", "ImageBrowser")
.CreateDirectory("CreateDirectory", "ImageBrowser")
)
.Render();
}
@Html.ValidationMessageFor(model => model.HelpContent)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.createDateTime, "Create Date")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.createDateTime)
@Html.ValidationMessageFor(model => model.createDateTime)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.modifiedDateTime, "Modified Date")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.modifiedDateTime)
@Html.ValidationMessageFor(model => model.modifiedDateTime)
</div>
<p>
<input id="btnEdit" type="submit" value="Save" />
<button id="btnCancel">Cancel</button>
</p>
</fieldset>
}