I need to initialize “ConditionalAnalysisInput” based on the selected value from the dropdown list above it. I will need access to dbset in order to do that.
What would be the best way to initialize the ConditionalAnalysisInput field?
Here’s the view code:
@using (Ajax.BeginForm("_ListConditionalAnalysis",
new AjaxOptions { UpdateTargetId = "_conditionals",
InsertionMode = InsertionMode.InsertAfter}))
{
@Html.DropDownListFor(model=>model.AvailableConstructs,Model.AvailableConstructs)
<p>
<input type="submit" value="Populate" />
</p>
}
<div id="_conditionals">
@*** Need to init ConditionalAnalysisInput here depending on the selected value from the dropdown list. Access to dbset needed *@
@foreach (var item in Model.ConditionalAnalysisInput)
{
@Html.Partial("_ListConditionalAnalysis",item)
}
</div>
You will really want to do a callback to the server to get the new model data which you need for the next section. Initializing models (and connecting to the database) are server-side responsibilities which should never be handled directly on the client.
I would create an action which takes the selected item and returns the list of ConditionalAnalysisInput objects which you need to deal with. Whenever the dropdownlist is changed, issue an AJAX call to get the new data and refresh your _conditionals div.
With the normal disclaimer that this is grossly oversimplified and not something you should just past in without cleaning it up, here’s a simple example I threw together to demonstrate what I mean:
I have two test models, which are obviously simplified. The first one would be for all of the data you need initially for the web page (i.e. the drop down list). The second model is for your partial view, which depends on the selected item from the dropdownlist:
Next the controller. The main action just populates the main model and returns the view. You also need to add a second method which takes the selected item as a parameter and returns a PartialViewResult:
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
public ActionResult Index()
{
var model = new DropDownModel(new List
{
“Option A”,
“Option B”
});
return View(model);
}
Create a “Conditionals” partial view which contains all of the markup you want to display in your _conditionals div:
On your main view, add a handler for the DropDownList’s change event. During the change event, you can issue a get request to the server to invoke the GetDataForDiv method, then update the _conditionals div with the resulting partial view. Here’s my example: