3

I have an Editor Template called "Address.cshtml" that has a model defined as:

@model Acme.Models.Address

In a View I want call the Editor Template and pass a local variable of the same type, and define the name it will use for the variables, I've tried a number of things including:

@Html.Editor("address", "Address", new { Model = address })

How do I pass the model?

Note, I cannot use @Html.EditorFor() because the view uses a different model.

5
  • You can still use EditorFor what I see Commented Feb 5, 2015 at 15:32
  • @EhsanSajjad how? When you reference the model it in the linq expression it is bound to the view's model, how do you override it to use a different object as the model? Commented Feb 5, 2015 at 15:34
  • 1
    You can do like EditorFor(x=> address) if address is variable in view it should work , but I m not sure , technically it should work Commented Feb 5, 2015 at 15:36
  • No, what it does is grabs the type of your variable, and if matches the template, then it just shows the View model property. You can see this when you hover over x because shows the name of the view's model. Commented Feb 5, 2015 at 15:42
  • I really don't understand what you're trying to do. Whenever you try to go against the grain of a framework, you should really consider WHY you want to do this.. chances are, you probably misunderstand what it is you are trying to do. Commented Feb 5, 2015 at 21:09

2 Answers 2

3

The only purpose of EditorFor is to work with your view's model. If you need to work with a completely different class instance that's not your view's model or accessible through you're view's model. Then just use Html.Partial. They're functionally the same. If you're worried about using a specific editor template, you can always pass the full path to the view to Html.Partial.

Sign up to request clarification or add additional context in comments.

2 Comments

Ended up using a Html.Partial. I didn't think EditorFor could be used for this, but I thought there might be a way to use Html.Editor() to pass an object that was the model for the Editor Template.
@Josh, @Html.EditorFor(m => m.Address) does pass the object to the EditorTemplate (assuming property Address is type of Acme.Models.Address)
0

In a view (in its header or somewhere else, but before the row you are calling your Html.Editor) you can add the model in the ViewData with the key equals to your Html.Editor's expression and it will be used as a model in your called editor. For example:

@{
    var address = new Acme.Models.Address();
    ViewData["address] = address;
}

@Html.Editor("address", "Address")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.