user295541
user295541

Reputation: 1015

ASP.NET MVC Binding issue

I have an object with a property called "name". This object has a sub object that has a property called "name" as well.

Transaction.name

Transaction.TransactionItem

TransactionItem.name

I bind Transaction object to a partial control as usual:

Html.TextBox("name", Model.name)%> 

Model is a Transaction object.

And I bind TransactionItems:

<%  if (Model.mtTransactionItem != null)
    {
         foreach (var item in Model.mtTransactionItem)
         { %>
    <tr>
        <td>
            <%= Ajax.ActionLink(item.name, "ShowItem", new { id = item.id }, new AjaxOptions { UpdateTargetId = "dialog-form" })%>
        </td>

And when I update the one of the transaction items through an ajax call I pass the entire transaction object to the partial view.

When I debug I check the Model.name property, and it has a proper value. But on the page shows the name of TransactionItem value instead of the name of Transaction value.

What am I doing wrong?

I have checked this problem in MVC 1.0 and MVC 2.0 framework.

Upvotes: 0

Views: 148

Answers (1)

LukLed
LukLed

Reputation: 31842

Your description is not clear to me, but I'll give you good advice. Instead of creating fields like that:

Html.TextBox("name", Model.name)

use

Html.TextBox("transaction.name", Model.Name)

and then

ActionResult Save(Transaction transaction);

Value of prefix has to be the same as parameter in function.

If you show components for items on the same page, use

Html.TextBox("transactionitems[i].name", Model.name)

or for one item

Html.TextBox("transactionitem.name", Model.name)

Don't use the same field name for different components on page, because it can cause problems with ModelState. Read about using prefixes, this will propably save some of your problems.

Also remember that with MVC 2 you have DataAnnotations, which make creating forms even easier.

Upvotes: 1

Related Questions