Shorthand for creating a ViewDataDictionary with both a model and ViewData items?

前端 未结 5 1075
死守一世寂寞
死守一世寂寞 2020-12-13 09:43

Is there any way to create a ViewDataDictionary with a model and additional properties with a single line of code. I am trying to make a RenderPartial

5条回答
  •  北海茫月
    2020-12-13 10:15

    I created an extension method on HtmlHelper to copy the property names and values from an anonymous object to a ViewDataDictionary.

    Sample

    Html.RenderPartial("SomePartialView", MyModelObject, new { SomeDisplayParameter = true })
    

    HtmlHelper Extension

    public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model, object viewData)
    {
        var vdd = new ViewDataDictionary(model);
        foreach (var property in viewData.GetType().GetProperties()) {
            vdd[property.Name] = property.GetValue(viewData);
        }
        htmlHelper.RenderPartial(partialViewName, vdd);
    }
    

提交回复
热议问题