bug ASP.NET MVC ModelBinder: la liaison des variables demande « id » à la propriété du modèle « Id »

StackOverflow https://stackoverflow.com/questions/5358913

Question

J'utilise MVC 3 RTM final.

Vu

Cette route:

context.MapRoute(
    "Blog_Posts",
    "Blog/Posts/{id}/{slug}",
    new { controller = "Posts", action = "Index", slug = UrlParameter.Optional }
);

Et sur la page d'un poste, par exemple / blog / messages / 2 / une limace je lie une vue partielle avec un modèle Comment:

@Html.Partial("_CommentEditor", new Comment())

Et Comment a public int Id {get; set;}.

Et dans la vue partielle, j'ai ceci:

@Html.HiddenFor(comment => comment.Id)

Pourquoi faut-il afficher cela?

<input type="hidden" value="2" name="Id" id="Id" data-val-required="The Id field is required." data-val-number="The field Id must be a number." data-val="true">

Et pourquoi quand je change Id sur Comment à CommentId-t-il correctement une valeur de 0?

Me pense que le modèle de liaison par défaut lie au {id} de la route.

Était-ce utile?

La solution

That's happens because when you are using HTML helpers such as HiddenFor they first look at route data and model state and after that in the model. So they find in your route data a parameter id=2 and use this value instead of the id=0 in the model you are passing.

Autres conseils

It is a bug or it might not because of below implemented logic;

In Asp.NET MVC, a View engine uses ViewData (it is variable and its type is "ViewDataDictionary"). And this ViewData has 2 properties "ModelState" that holds routing values, and "Model" that holds our actual model object.

  1. A View engine looks into "ModelState" object retrieving value of a property.
  2. If found in step 1 then return value.
  3. Else looks into "Model" object to retrieve value for a property.

In above case, route has property "id" and its value are saved in "ModelState" so it return value from "ModelState" instead of binded model.

For above scenario, any input control renders with unexpected value.

Resolution is:

<div class="postData" value='@Model.Id'/>

//use below jquery function to retrieve data
var postedData = $('.postData');

If you're using linq to sql, fields marked as provided by database cannot be set manually.

Try:

Try @Html.Partial("_CommentEditor", new Comment{Id = 0}) 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top