简体   繁体   中英

Creating partial view with dynamic content

I understand when I create a view, I shouldn't be putting any code in there besides html and the data from the model/controller, which is what I've done so far.

But lets say there is a snipped of dynamically generated html that can be used in multiple views, I'm guessing this would be a partial view that goes in the Shared folder in the project. But since it's a partial view, that has no absolute controller to handle it's propagation of dynamic data (from db), how would I call, and where would I code the propagation of data from the db into the view (or model?), if lets say the partial view was to dynamically render content for table.id=n , etc.

I'm fairly to new and working off a tutorial in .net, trying to figure out how to do this. Anyone know how it's done? Hope the question makes sense.

You can always define a model for the partial.

And you can render the partial from the container view passing a dinamically populated instance of its model:

<!-- index.cshtml -->
<h1>Feed Upload</h1>
<div id="uploader">
        @Html.Partial("~/Views/Shared/Controls/_FileUploader.cshtml", new FileUploaderModel() { UploaderClassName = this.Model.UploaderClassName })
</div>

In this simple example I call the partial _FileUploader.cshtml from the index.cshtml using the @Html.Partial() method, passing a new model instance that specifies the UploaderClassName value.

Edit

The this.Model.UploaderClassName refers to the container 's model and it is initialized inside the container 's controller business. Of course the container 's controller can run any data access logic to grab dynamic data from the db and pass them to the partial's model.

Have a look at MSDN , and at this article .

Assuming you are using the razor view engine, you can put an .cshtml file in the App_Code folder with helper functions.

The syntax is like this:

@helper FormatDate(DateTime date)
{
    @date.ToShortDateString()
}

You call it like this (assuming the file is Utility.cshtml)

@Utility.FormatDate(Patient.DOB)

Because you can pass parameters to a helper, you can pass any type you need, including complex objects.

I recently published a nuget package to do this very thing. It's called Dynamic MVC.

http://dynamicmvc.com

You can look at the source code on codeplex.

https://dynamicmvc.codeplex.com

The way I did this was to use the ModelMetadata engine built into MVC to allow me get the value for any property in a weakly typed fashion. The ModelMetadata engine originally came from ASP.net Dynamic Data and was ported over to MVC in MVC2. It works great for this kind of situation.

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