views:

20

answers:

1

Hi

What I can do: I aim to create a view where a User Control consisting of a TextBox and a Table is added to a page as needed. The user will type a SQL query in the textbox and the Table will be used to render the results.

What I need to do: I need to add multiple of these controls to the page as the user requests them. They'll be numbered in steps.

For example:
Step 1 = sql query to get a list of parameters; Step 2 = sql query which uses the first parameter to return a certain value; Step 3 = sql query that returns a cumulative sum of values which will be compared to the value in step 2.

Each time the "Add" button is clicked a new user control appears beneath the previous in which I can create my SQL query and produce my answer.

I can do the comparisons and query the database. No issues, I'm just not sure how to re-use controls in MVC.

Any suggestions would be helpful, Thanks, George

A: 

What you're trying to do is interesting and complicated. I trust you have the logic of the solution well in hand, so I will focus on the simple question you posed: "[How can I] add multiple instances of a user control to a single view page?"

There are, of course, a few ways you could do this. You can use javascript to clone a block of template html code, which is I would probably do so that I don't have a postback. However, you didn't mention javascript, so you should simply wrap your call to RenderPartial in a foreach loop and feed the loop with an incremental value or a list.

View.aspx:

<% 
//loop over sqlQueries in list, rendering a 
//  partial for each and passing the query into the partial.
foreach(var item in Model.listOfSqlQueries)
    Html.RenderPartial("sqlBox", item);
%>     

Then, have a button in the view that posts to an ViewResult and returns the same list plus one item.

Controller.cs:

public ViewResult AddQueryBox(ViewModel viewModel) 
{
    //Add blank sql query to list
    viewModel.listOfSqlQueries.Add(new SqlQuery());

    //return calling view with newly updated viewmodel
    return View("View", viewModel);
}
Byron Sommardahl
Ok, this makes sense, however let's say I have already entered a query and received the result as part of Step 1, If I add (by pressing the button) the second step, then the first query will be re-executed (unless I suppose I do a "check if queryresult = True) statement.
vwdewaal