Html.Serialize返回NullReferenceException

时间:2012-08-29 20:26:49

标签: asp.net-mvc

我有一个类似

的ViewModel
namespace ViewModel
{
    [Serializable]
    public class TestViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

另外,我有一个动作方法:

public ActionResult Index()
{
    TestViewModel model = new TestViewModel
    {
        Id = -1,
        Name = "Some name",
        Description = "Some description"
    };

    return View(model);
}

我的观点是这样的:

@using Microsoft.Web.Mvc
@model ViewModel.TestViewModel

@using (Html.BeginForm())
{
    Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned);
    //....Editor fields
}

符合“Html.Serialize(”model“,Model,SerializationMode.EncryptedAndSigned);”调试器停止并返回异常“对象引用未设置为对象的实例”(NullReferenceException)。虽然,Model不是null并且包含初始值。

我使用ASP.Net MVC 3(Razor),堆栈跟踪如下:

in Microsoft.Web.Mvc.SerializationExtensions.SerializeInternal(HtmlHelper htmlHelper, 
String name, Object data, SerializationMode mode, Boolean useViewData, MvcSerializer
serializer) 
in Microsoft.Web.Mvc.SerializationExtensions.SerializeInternal(HtmlHelper htmlHelper,
String name, Object data, SerializationMode mode, Boolean useViewData)
in Microsoft.Web.Mvc.SerializationExtensions.Serialize(HtmlHelper htmlHelper, String
name, Object data, SerializationMode mode)
in ASP._Page_Views_Wizard_Index_cshtml.Execute()
in c:\Projects\TestProject\Views\Wizard\Index.cshtml:line 15
in System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
in System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
in System.Web.WebPages.StartPage.RunPage()
in System.Web.WebPages.StartPage.ExecutePageHierarchy()
in System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,
TextWriter writer, WebPageRenderingBase startPage)
in System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer,
Object instance)
in System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter
writer)
in System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
in System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult actionResult)
in System.Web.Mvc.ControllerActionInvoker.
<>c__DisplayClass1c.InvokeActionResultWithFilters>b__19()
in System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, 
ResultExecutingContext preContext, Func`1 continuation)

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

您需要使用

@Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned)

如果您想在表单上使用模型隐藏字段。

答案 1 :(得分:0)

问题是我有对Mvc2Futures(“Microsoft.Web.Mvc.dll”)的汇编引用。但是当我更改了对Mvc3Futures(“Microsoft.Web.Mvc.dll”)的引用时,一切正常。 非常感谢。