0

I have a simple Action in my Controller:

    public ActionResult Edit(int itemId)
    {
        return View(new EditModel() { ItemId = itemId + 1 });
    }

    public class EditModel
    {
        public int ItemId { get; set; }
        public string Title { get; set; }
    }

The problem comes in the View, when I try to display everything.

Model.ItemId: @Model.ItemId
@Html.EditorForModel()

Since action parameter and property on EditModel have the same name (itemId) I get the following:

enter image description here

Is this a correct behaviour? How can I change default value displayed inside a form in that case?

2
  • I know the solution :) This just hadn't seem to be a correct behavior to me - because it really can confuse Commented Sep 1, 2011 at 13:58
  • Yes it is confusing. Yesterday I spent half of a day trying to resolve simmilar issue. Commented Sep 1, 2011 at 14:18

2 Answers 2

2

This may be somehow confusing for the first look, but yes, this is default(correct) behavior. Controller.ModelState is the privileged supplier for the values when you use EditorFor or similar editor helpers, over the model itself. But there's trickier point in your situation.

ModelState is populated with action parameters and values that take part in model binding. When you call that action, ModelState is populated with "ItemId" = action parameter(itemId) value. Later, EditorFor sees that is should draw editor for ItemId. As ModelState has already got ItemId, it does not look at model value, but extracts it from ModelState["ItemId"]. Tricky source of your error is that action parameter name matches the model property name and modelState prefers that over model value. The best solution (clean one) would be to just rename action parameter, so that it does not match the model property name.

public ActionResult Edit(int initialItemId)
        {
            return View(new EditModel() { itemId = initialItemId + 1 });
        }

This will do the trick.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I understand why it is so. The easiest solution is to rename, yes (in my real task there's even no need to rename, because that behavior suits me :)), it would be just good if VS or something notified about that, because I can easily imagine hours of debugging, when this "trick" will be used unintendedly :)
0

You can write

Model.ItemId: @Model.ItemId
@Html.EditorFor(x => x.Title)

Or hide ItemId for edit with metadata

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.