简体   繁体   中英

ASP.NET MVC. How render a Partial with no model (like create view)

I would like to render partial like this:

@Html.Partial("_MyPartial")

However my partial does need a typed object, for instance: MyPartial.cshtml :

@model MyApplication.Models.MyClass
(...)

But I would like to render it on my view WITHOUT a initialized model, like a "Create" view.

Create views is bound to a model, but is initialized empty.

What I already tried:

@Html.Partial("_MyPartial") The main view model is passed to the partial and it throws an incompatible types error.

@Html.Partial("_MyPartial", null) throws same error.

@Html.Partial("_MyPartial", new MyClass()) initializes view with default values. I don't want pre initialized view.

In a "Create" view, no model is passed to the view, BUT the view is bound to a model. I would like to render this partial in a "create" view. It must no be bound to a initialized model instance. It must be initialized empty.

In the fact, this is not possible, cause partial gets the model from the main view, if there is no one from itself.

In this case you must initialize the call partial and pass not only the model as null but the entire data from the context must be cleaned.

You have already write code to accept model type in view:

@model MyApplication.Models.MyClass

So it is compulsory that you have to pass model in view.

If you don't wants to use model then remove your code which accept model

Try to use html.renderaction instead of doing partial like this and dont declare any model for the view, if it really dont use one in the first place?

Oh yeah return a partialview in the action return and dont forget the curly braces after @ sign, it matters

When you want to return a partialview with no model. Use this.

@{ Html.RenderPartial("Your partial view") }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM