Reputation: 6944
Is it possible to change display order of divs when rendering View Page on Server Side? Every single div has different c# and html content, so it's not possible to generate them by loop.
One option is display as is and reordering in client side when page OnReady by jQuery. But it has some delay time to rearrange divs.
Another option is generate view page for every div, then loop div ids, render content with @Html.Action
or @Html.RenderPartial
. It is not feasible when items are >20 and pages are >100
Any solution on server side would be appreciated.
Foo.cshtml page:
<div class="container">
<div id="a">
//some c# codes to render html
</div>
<div id="b">
//some other c# codes to render html
</div>
<div id="c">
//some another c# codes to render html
</div>
</div>
When Cookie value for ViewOrder: c,b,a
Expected output:
<div class="container">
<div id="c">
//some another c# codes to render html
</div>
<div id="b">
//some other c# code to render html
</div>
<div id="a">
//some c# codes to render html
</div>
</div>
Possible solution on client side with jQuery
$.fn.orderChildren = function(order) {
this.each(function() {
var el = $(this);
for(var i = order.length; i >= 0; i--) {
el.prepend(el.children(order[i]));
}
});
return this;
};
$(".user").orderChildren(["c","b","a"]);
Upvotes: 0
Views: 2010
Reputation: 14007
If you don't want to create partials (which I would still consider feasible, since you have the markup anyway in your page), you can loop over your search predicates and use switch
to render your parts:
Your controller would add the order to your model:
//Model
class MyModel {
//...
public string[] DivOrder { get; set; };
//...
}
//Controller Action
MyModel model = new MyModel();
//...
model.DivOrder = new { "c", "b", "a" };
//...
Your view would rearrange the output based on the order:
<div class="container">
@foreach(string key in Model.DivOrder) {
switch (key) {
case "a":
<div id="a">
//some c# codes to render html
</div>
break;
case "b":
<div id="b">
//some other c# codes to render html
</div>
break;
case "c":
<div id="c">
//some another c# codes to render html
</div>
break;
}
}
</div>
Upvotes: 1
Reputation: 37215
For server-side reordering in cshtml, split the ViewOrder into an array of strings and iterate through it:
foreach(var div in ViewOrder.Split(",".ToCharArray()) {
switch (div) {
case "a":
<div id="a">
//some c# codes to render html
</div>
break;
case "b":
<div id="b">
//some c# codes to render html
</div>
break;
... etc ...
}}
Note that there is also a CSS solution using FlexBox and the CSS order:
attribute, as illustrated in this answer.
Upvotes: 1