相关疑难解决方法(0)

Asp.net MVC ModelState.Clear

任何人都可以给我一个关于ModelState在Asp.net MVC中的角色的简洁定义(或者链接到一个).特别是我需要知道在什么情况下打电话是必要的或可取的ModelState.Clear().

有点开放了 ......对不起,我想如果告诉你我在做什么可能会有所帮助:

我在一个名为"Page"的控制器上有一个Edit of Action.当我第一次看到表单更改页面的详细信息时,所有内容都很好地加载(绑定到"MyCmsPage"对象).然后,我单击一个按钮,为MyCmsPage对象的某个字段(MyCmsPage.SeoTitle)生成一个值.它生成正常并更新对象,然后我返回动作结果与新修改的页面对象,并期望相关的文本框(使用渲染<%= Html.TextBox("seoTitle", page.SeoTitle)%>)更新...但是它显示了加载的旧模型的值.

我通过使用来解决它,ModelState.Clear()但我需要知道它为什么/如何工作所以我不只是盲目地做.

的PageController:

[AcceptVerbs("POST")]
public ActionResult Edit(MyCmsPage page, string submitButton)
{
    // add the seoTitle to the current page object
    page.GenerateSeoTitle();

    // why must I do this?
    ModelState.Clear();

    // return the modified page object
     return View(page);
 }
Run Code Online (Sandbox Code Playgroud)

ASPX:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyCmsPage>" %>
....
        <div class="c">
            <label for="seoTitle">
                Seo Title</label>
            <%= Html.TextBox("seoTitle", page.SeoTitle)%>
            <input type="submit" value="Generate Seo Title" name="submitButton" />
        </div>
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc post-redirect-get modelstate

114
推荐指数
6
解决办法
10万
查看次数

asp.net mvc控制器发布最佳实践

我对使用问题的"最佳实践"控制器感到有点困惑.

我典型的代码看起来

    public ActionResult Edit(int reportId,FormCollection formCollection)
    {
        try
        {
            var report = _dbContext.EmployeeReports.Find(reportId);

            if (TryUpdateModel(report))
            {
                _employeeReportService.Update(report);
                return RedirectToAction("List");
            }

            return View("Edit", report);
        }
        catch (Exception)
        {
            // some logging etc
            return RedirectToAction("List");                
        }
Run Code Online (Sandbox Code Playgroud)

好吧,最好使用"TryUpdateModel"或仅使用"UpdateModel"或简单调用Model.IsValid并且最好在控制器中捕获异常?

谢谢

asp.net-mvc controller asp.net-mvc-3

2
推荐指数
1
解决办法
1918
查看次数