ModelState
. Post-Redirect-Get을 따라 TempData
으로 전송할 수 있습니다. 예 :
[HttpPost]
[ExportModelStateToTempData]
public ActionResult Delete(int id)
{
if (_service.DeleteTask(id))
return RedirectToAction(ControllerActions.Index);
return RedirectToAction(ControllerActions.Edit, new { id });
}
[ImportModelStateFromTempData]
public ActionResult Edit(int id)
{
var task = _service.GetTask(id);
return View(ControllerActions.Edit, GetEditModel(task));
}
사용자가/callig/작업으로 작업을 삭제 삭제 작업을하지만, 뭔가 잘못과 오류 메시지가 나타나는 경우, F5를 누르면 다시 삭제를 호출하지 않습니다 수 있습니다. 이후 ModelState
을 Edit
으로 전송하면 모든 오류가 편집 페이지에 표시됩니다.
public abstract class ModelStateTempDataTransferAttribute : ActionFilterAttribute
{
protected static readonly string Key = typeof(ModelStateTempDataTransferAttribute).FullName;
}
public class ExportModelStateToTempDataAttribute : ModelStateTempDataTransferAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
//Only export when ModelState is not valid
if (!filterContext.Controller.ViewData.ModelState.IsValid)
{
//Export if we are redirecting
if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
{
filterContext.Controller.TempData[Key] = filterContext.Controller.ViewData.ModelState;
}
}
base.OnActionExecuted(filterContext);
}
}
public class ImportModelStateFromTempDataAttribute : ModelStateTempDataTransferAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary;
if (modelState != null)
{
//Only Import if we are viewing
if (filterContext.Result is ViewResult)
{
filterContext.Controller.ViewData.ModelState.Merge(modelState);
}
else
{
//Otherwise remove it.
filterContext.Controller.TempData.Remove(Key);
}
}
base.OnActionExecuted(filterContext);
}
}
매우 문제가 될 것 Model
과 같은 일을 :
이 ModelState
수출 수입 속성/대한 코드입니다.
당신의'ControllerActions' 클래스는 무엇입니까 ? 그것은 저에게 새로운 것입니다. –
@Matt Greer : 그것은 행동의 상수 이름을 가진 클래스 일뿐입니다. 강하게 입력해야합니다. 형형색색의 타이핑 된 이름으로 연주하고 싶다면 T4MVC를 사용하는 것이 좋습니다. – LukLed
그래서 그냥 const 문자열의 모음? Drat, 나는 당신이 마법의 끈을 피할 수있는 영리한 해결책이 있기를 바랬습니다. 매직 문자열은 최근에 가장 큰 애완 동물이되었습니다. NET : –