5

I recently started to use a viewModel. Here's the viewModel I am using:

public class ContentViewModel
    {
        public Content Content { get; set; }
        public bool UseRowKey { 
            get {
                return Content.PartitionKey.Substring(2, 2) == "05" ||
                   Content.PartitionKey.Substring(2, 2) == "06";
            }
        }
        public string TempRowKey { get; set; }

    }

I changed my razor views from:

@model WebUx.Content

<div class="colx2-left">
    <label for="complex-fr-url" class="required">Order</label>
    @Html.TextBoxFor(model => model.Order)
</div>

to:

@model WebUx.Areas.Admin.ViewModels.Contents.ContentViewModel

<div class="colx2-left">
    <label for="complex-fr-url" class="required">Order</label>
    @Html.TextBoxFor(model => model.Content.Order)
</div>

Now my views fail with the following message:

Compiler Error Message: CS0411: The type arguments for method System.Web.Mvc.Html.InputExtensions.TextBoxFor TModel,TProperty> (System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>) cannot be inferred from the usage. Try specifying the type arguments explicitly.

Can someone give me advice about what I should do?

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

2

As a rule of thumb, i ensure my Views/templates only reference a property within the model it's dealing with, not one under.

Your first attempt before your change was correct.

So, i would change your View to the following:

@model WebUx.Areas.Admin.ViewModels.Contents.ContentViewModel
@Html.EditorFor(model => model.Content)

And make use of your existing template:

@model WebUx.Content
<div class="colx2-left">
    <label for="complex-fr-url" class="required">Order</label>
    @Html.TextBoxFor(model => model.Order)
</div>

Also i have no idea about what Order is. If it's not a string, then that's also going to be an issue.

RPM1984
  • 72,246
  • 58
  • 225
  • 350
1

Make sure Order is a public property on Content. Right now I got this exception while implementing a POC app. Guess what? I forgot to add the public specifier in front of my ViewModel properties.

I had this:

public class UserViewModel
{
    [StringLength(16)]
    string Name { get; set; }

    [Range(18, 65)]
    int Age { get; set; }
}

and then that same exception you got was being thrown here.

I did this to fix the problem:

public class UserViewModel
{
    [StringLength(16)]
    public string Name { get; set; }

    [Range(18, 65)]
    public int Age { get; set; }
}
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480