0

I have ViewModel for example

class CustomerViewModel {
// ...
public string Name {get; set;}
public CategoryViewModel CategoryVM {get; set;}
}

class CategoryViewModel {
// ... 
public string Name {get;set;}
}

In View i can get Id of an html element with html helper

<!-- Customer Name -->
@Html.IdFor(m => m.Name)

<!-- Category Name -->
@Html.IdFor(m => m.CategoryVM.Name)

But what if CategoryVM is inserted into PartialView

@{Html.RenderPartial("~/.../_Category.cshtml", Model.CategoryVM);}

How to get Id of the property ? Because now i have two id's with same name. What is best practice for properties naming and handling in nested ViewModels ?

Also i dont want to pass whole Model to the PartialView because there are Ajax calls, which re-renders the partial view, and i dont want to build whole Model from scratch even for simple operations.

Muflix
  • 6,192
  • 17
  • 77
  • 153
  • 1
    I don't understand what is your issue. you could use `@Html.IdFor(m => m.Name)` inside your partial view . Your model inside of partial view is `Model.CategoryVM` . – Hadee Nov 20 '16 at 21:29
  • 1
    Having duplicate `id` attributes is invalid html. And do not use partial views for nested objects (although you can is you pass the `HtmlFieldPrefix` as per [this answer](http://stackoverflow.com/questions/29808573/getting-the-values-from-a-nested-complex-object-that-is-passed-to-a-partial-view/29809907#29809907)) Use an `EditorTemplate` so you iputs are correctly named. –  Nov 20 '16 at 22:25
  • @Hadee: because i need to use the Id selector in the javascript and i dont have that javascript in the partialview to prevent re-rendering static script. – Muflix Nov 21 '16 at 12:30
  • @StephenMuecke i will try the HtmlFieldPrefix, that seems very good thank you, but i dont understand why not to use partial view for nested object ? – Muflix Nov 21 '16 at 12:31
  • 1
    Look at the html your generating for the nested object - it does not have the correct prefix (which needs to be `CategoryVM.Name`). And use an `EditorTemplate`, not the `HtmlFieldPrefix` –  Nov 21 '16 at 12:33
  • @StephenMuecke I will try it, but is there a reason to use EditorTemplate rather then HtmlFieldPrefix ? because Prefix seems to solve my problem and it seems simpler. – Muflix Nov 21 '16 at 13:59
  • 1
    Simpler?? Just rename you partial to `CategoryViewModel.cshtml` (to match the name of the class) and move it to the `/Views/Shared/EditorTemplates` folder. Then in the main view its `@Html.EditorFor(m => m.CategoryVM)` - why - because that what `EditorTempates` are designed for! –  Nov 21 '16 at 23:09
  • and that template file can be returned as partial view via ajax, (when i need to rerender the controls) great! only the "shared" folder can be confusing, because viewmodel is used only one – Muflix Nov 22 '16 at 22:43

0 Answers0