Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UpdateModel prefix - ASP.NET MVC

Tags:

asp.net-mvc

I'm having trouble with TryUpdateModel(). My form fields are named with a prefix but I am using - as my separator and not the default dot.

<input type="text" id="Record-Title" name="Record-Title" />

When I try to update the model it does not get updated. If i change the name attribute to Record.Title it works perfectly but that is not what I want to do.

bool success = TryUpdateModel(record, "Record");

Is it possible to use a custom separator?

like image 283
Kristoffer Ahl Avatar asked Dec 07 '08 12:12

Kristoffer Ahl


1 Answers

Another thing to note is that the prefix is to help reflection find the proper field(s) to update. For instance if I have a custom class for my ViewData such as:

public class Customer
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

public class MyCustomViewData
{
    public Customer Customer {get; set;}
    public Address Address {get; set;}
    public string Comment {get; set;}
}

and I have a textbox on my page

<%= Html.TextBox("FirstName", ViewData.Model.Customer.FirstName) %>

or

<%= Html.TextBox("Customer.FirstName", ViewData.Model.Customer.FirstName) %>

here is what works

public ActionResult Save (Formcollection form)
{
    MyCustomViewData model = GetModel(); // get our model data

    TryUpdateModel(model, form); // works for name="Customer.FirstName" only
    TryUpdateModel(model.Customer, form) // works for name="FirstName" only
    TryUpdateModel(model.Customer, "Customer", form); // works for name="Customer.FirstName" only
    TryUpdateModel(model, "Customer", form) // do not work

    ..snip..
}
like image 128
Todd Smith Avatar answered Nov 23 '22 11:11

Todd Smith