How to prevent view from passing its model to the

2019-04-22 19:09发布

In ASP.NET MVC and using Razor, I have a View (parent) calling another View (child) as partial. Both are strongly typed but they have a different Model type.

Normally, in these situations, we pass a Model explicitly from the parent View to the child View.

@Html.Partial("Child", Model)

We can also choose not to specify explicitly a Model to be passed and, in those cases, the parent View will attempt to pass its own Model to the child View. This works if the types match and it is desirable in most cases.

@Html.Partial("Child")

In my case, however, I really want the parent View not to try to pass anything to the child View. How would I do that?

I thought of attempting to pass null explicitly:

@Html.Partial("Child", null)

But this still passes the parent's Model to the child View, resulting in an error: The model item passed into the dictionary is of type 'A', but this dictionary requires a model item of type 'B'.

(As a side note, the child View is a Create View for its model, that's why I don't have an instance to pass to it.)

3条回答
孤傲高冷的网名
2楼-- · 2019-04-22 19:39

Try this:

@Html.Partial("Child", null, new ViewDataDictionary<ChildType>(childInstance/*this can be null*/))
查看更多
对你真心纯属浪费
3楼-- · 2019-04-22 19:43

I understand the reason you want to not pass the model is so that your inputs are emptied out? If this is the case, you can rather pass a new Model to this partial:

@Html.Partial("Child", new Model())

Since the Model is new, it won't have any values populated.

查看更多
乱世女痞
4楼-- · 2019-04-22 19:46

You could have your create form not strongly typed... craft your inputs in order to once posted you will have a model binded in your controller action.

Now... for me it doesn't worth the work just for the conceptual subtlety of "Model not existing yet" (AKA not in database yet).

In my case I create dummy models just to set default values in certain fields (for instance: setting today date, default values in dropdownlists, etc.)

查看更多
登录 后发表回答