开发者

ASP.NET MVC model bind ID mismatch

开发者 https://www.devze.com 2022-12-19 09:51 出处:网络
I have a View in MVC 2 where I edit a \"Page\". A Page has a Name, Title and Content. Content is of type EditableContent, which has Width, CssClass and Columns. Columns is a List.

I have a View in MVC 2 where I edit a "Page". A Page has a Name, Title and Content. Content is of type EditableContent, which has Width, CssClass and Columns. Columns is a List.

When I do this in the view:

<%= Html.TextBoxFor(m => m.Name) %>

It outputs the following HTML:

<input type="text" value="About Page" name="Name" id="Name">

And when I post to the Edit action in ContentController:

/// <summary>
/// Edits the specified form.
/// </summary>
/// <param name="item">The content page.</param>
/// <returns>Acti开发者_开发百科onResult for edit</returns>
[HttpPost]
public ActionResult Edit(Page item)
{
    if (ModelState.IsValid)
    {
    }

    return View(item);
}

It cannot bind the Name property to item.Name. Looking up the values in Request.Form, I see the Name parameter.

If I render the textbox manually, using this:

<%= Html.TextBox("item.Name", Model.Name)%>

The value is binded perfectly to the Page instance in the controller action.

Am I doing something fundamentally wrong here?


If your action method parameter is named item, the DefaultModelBinder will look for item.name, item.title, item.content.width, etc. If it can't find any *item.** in the request, it will ignore the item prefix and fall back to the empty prefix, looking just for name, title, content.width, etc.

Chances are something else in the request is called item (or *item.**), which is causing this fallback logic not to occur. If you want to force the fallback logic, attribute the parameter with [Bind(Prefix = "")], which says "yeah, I know this parameter was named item, but pretend its name is actually ''."


Just off the top of my head, have you tried entering the full namespace for your Page parameter in your Action? There may be a naming conflict.


You have to use prefixes for model names. This will isolates input for different models. Example of action

public ActionResult Edit([Bind(Prefix="Page")]Page item)

{...}

when rendering input

<%= Html.TextBox("Page.Name", Model.Name)%>

Sorry, don't now how to do this using helper with lambda expression.

0

精彩评论

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

关注公众号