How do you reuse a partial view with setting different ids
I have a partial view with a dropdown in it. the code looks like this:
<%=Html.DropDownListFor(x => Model.Exercises, new SelectList(Model.Exercises, "Id", "Name", Model.SelectedExercise), new { @id = "exerciseDropdown", @class = "autoComplete" })%>
The issue is that I want to reuse this partial view in multiple places but I want to have a different id assigned to the contr开发者_JS百科ol (instead of exerciseDropdown always) but on the outside I only have this:
<% Html.RenderPartial("ExerciseList", Model); %>
Is there anyway to pass in an id into a partial view? Is there a standard way to inject the ids into a partial view?
Right now I am doing things like this:
<% Html.RenderPartial("ExerciseList", Model); %>
<% Html.RenderPartial("ExerciseList2", Model); %>
where ExerciseList and ExerciseList2 are identical but with different ids but I am sure there is a better way.
It sounds like you are using the same model to do both partial views. I see two options for setting this up.
- Like Nick said above, use a partial class and add the dropDownID property to your model.
**Warning Pseudo VB Code ahead
Partial Public Class Exercise
Dim _ddID as string
Public Property DropDownID as string
Get
Return _ddID
End Get
Set(byval value as string)
_ddID = value
End Set
End Property
Then in your controller:
Function Index() as ActionResult
Exercise = getExercise() 'call to get your exercise model'
Exercise.DropDownID = "DropDownID1"
Return View(Exercise)
End Function
View:
<%=Html.DropDownListFor(x => Model.Exercises, new SelectList(Model.Exercises, "Id", "Name", Model.SelectedExercise), new { @id = model.DropDownID, @class = "autoComplete" })%>
Option 2: Set in your ViewData dictionary
Controller:
Function Index() as ActionResult
Exercise = getExercise() 'call to get your exercise model'
ViewData("ExerciseID") = "DropDownID1"
Return View(Exercise)
End Function
Call Partial View:
<% Html.RenderPartial("ExerciseList", Model, ViewData); %>
View:
<%=Html.DropDownListFor(x => Model.Exercises, new SelectList(Model.Exercises, "Id", "Name", Model.SelectedExercise), new { @id = ViewData("ExerciseID"), @class = "autoComplete" })%>
You could just include the id you want to use in the model.
In my case, I wanted different IDs because jQuery calendar was failing to write date to the required input field. Instead, it was writing date into the first field with the same ID.
So, I wasn't really concerned with the ID. So used something like this-
@Html.TextBoxFor(model => model.DueDate, new Dictionary<string, Object> { { "class", "datepicker" }, { "id", Guid.NewGuid().ToString() } })
精彩评论