开发者

c# MVC Add multiple instances of a user control to a single view page

开发者 https://www.devze.com 2023-01-07 02:21 出处:网络
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开发者_如何学Go a SQL query in the textbox and the Table w

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开发者_如何学Go 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


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消