开发者

MVC2: Can't convert String to ExtensionDataObject (without knowing I wanted to)

I'm开发者_高级运维 getting the following InvalidOperationException:

The parameter conversion from type 'System.String' to type 'System.Runtime.Serialization.ExtensionDataObject' failed because no type converter can convert between these types.

In a Post action on my ASP.Net MVC2 page, but I'm really not sure what it's referring to. I'm using data annotation validation:

public class FamilyPersonMetadata
{
    [Required(ErrorMessage = "Name Required")]
    public String Name;

    [Required(ErrorMessage = "Date of Birth required")]
    [DateTime(ErrorMessage = "Invalid Date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d")]
    public DateTime DateOfBirth;
}

[MetadataType(typeof(FamilyPersonMetadata))]
public partial class FamilyPerson
{
}

And my view inhertis from a ViewPage with a subtype of FamilyPerson. I just create controls with names matching those of FamilyPerson and then submit the form, but for some reason my ModelState is invalid and the above error is apparently the reason. I'm quite perplexed as to the nature of the error. Similar code is working for other views and actions.

Could someone point me in the direction of things to look at that might cause this?


Regarding [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d")]

"{0:d" should be "{0:d}"


Here's an actual explanation of the problem, and how to solve it: http://www.shawson.co.uk/codeblog/mvc-strongly-typed-view-returns-a-null-model-on-post-back/comment-page-1/

Short summary: Don't give your view parameters the same names as model fields, unless they represent the same value (and have the same type).


It seems to have gone away on its own. Weird.


This may help someone:

I had this exception being thrown because i had mulitiple forms in my view.

However one of the forms did not explicitly set the 'action' attribute. That is, i was using this constructor:

@using (Html.BeginForm())

Instead of this one:

@using (Html.BeginForm("ACTION_METHOD", "CONTROLLER", FormMethod.Post, null))

This would result in the incorrect parameters being posted with the Form. Spoecifically, the business model object was being included on the Form when it shouldn't be. In turn, .Net was then trying to convert a System.String to a business model object when it shouldn't be attempting such a conversion.

The solution is to use the later overloaded method and ensure that the correct 'action' attribute is being set for your Form upon postback.

FYI: To inspect the 'action' attribute of your Form, use FireBug and inspect the HTML, find the Form element and the 'action' attribute will be there with all the parameters that will be posted back to the serber when that Form is submitted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜