0

我有一个接受对象的 ASP.NET MVC 3 控制器操作,如下所示:

    //// model.ReferenceNumber equals "-1"
    public ActionResult EditApplication(EditApplicationViewModel model)
    {
        if (!ModelState.IsValid)
        {
                  ...
        }

        // Existing Applicant
        model.ReferenceNumber = "";
        var msg = this.RenderPartialViewToString("_ExistingApplication", model);
    }

当收到请求时,“model.ReferenceNumber”等于“-1”。即使将模型上的属性设置为空字符串“”,“RenderPartialViewToString”的结果仍然会在“输入”HTML 字段的“值”属性中显示“-1”的值。

知道为什么会这样吗?

这是用于渲染局部视图的代码: http: //craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/

public static string RenderPartialViewToString(this Controller controller, string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

    controller.ViewData.Model = model;

    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
        var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

谢谢

4

1 回答 1

1

当您在控制器 qc​​tion 中修改某些模型属性的值时,请确保也将其从模型状态中删除:

ModelState.Remove("ReferenceNumber");
model.ReferenceNumber = "new value";
var msg = this.RenderPartialViewToString("_ExistingApplication", model);
于 2012-05-10T09:33:47.980 回答