How can I query the database using Web Matrix to get a single item by passing the ID in from another page?
Note: I'm using partial pages for alot of my UI, these are just pages in webmatrix, using:
@RenderPage("/page_name.cshtml")
I'm trying to compose a <ul>
from two tables and pages. A Services table which has an associated ServiceFeatures table. It WebMatrix it picks up the relationship by assigning a serviceID to the ServieFeatures table, that is the ServieId of the Services table.
So I have two pages to render the <ul>
one _ServiceList.cshtml which has the following:
@{
var db = Database.Open("winmodb");
var servicesSql = "SELECT * FROM Services WHERE Featured = 'true'";
var services = db.Query(servicesSql);
}
<div id="service-list">
@foreach(var service in services) {
<h2>@s开发者_如何学运维ervice.Name</h2>
<ul>
@RenderPage("~/shared/_ServiceFeature.cshtml", @serviceId);
</ul>
}
And inside of _ServiceFeature.cshtml I have the following.
@{
var db = Database.Open("database");
var serviceFeatureSql = "SELECT * FROM ServiceFeatures WHERE ServiceId = @0";
var serviceFeature = db.QuerySingle(serviceFeatureSql, serviceId);
}
<li>@serviceFeature.Name</li>
But it's not working, and I'm not sure if I have to pass a variable or not. I know that serviceId dosen't exist in the current context, this is where I'm stuck.
In the _ServiceList page, your RenderPage call should look like this:
@RenderPage("~/shared/_ServiceFeature.cshtml", service.serviceId)
In _ServiceFeature, you can obtain the value of the serviceId using Page[0]:
db.QuerySingle(serviceFeatureSql, Page[0]);
Parameters are passed in the PageData
(non-dynamic) or Page
(dynamic) properties:
@RenderPage("~/shared/_ServiceFeature.cshtml", new { serviceId });
In the partial page, you can write
db.QuerySingle(serviceFeatureSql, Page.serviceId);
In order to access parameters by name, you need to pass then as an anonymous type.
精彩评论