Apply specific width in column of WebGrid in MVC3

2020-02-05 04:29发布

问题:

I Have used WebGrid to take benefit of inbuilt sorting and paging in MVC application and it's worked very well only one issue i could not fix and looking here for anyone's help

My webgrid is look like as per below

@{
        var grid = new WebGrid(Model, canSort: true, canPage: true, rowsPerPage: 10);
        grid.Pager(WebGridPagerModes.NextPrevious);
        @grid.GetHtml(columns: grid.Columns(

        grid.Column("Name", "Name", canSort: true),
        grid.Column("Address", "Address", canSort: true),        
        //other columns
        ));
  }

How can i fixed the width of every column as per my requirement? (need different width for different column)

回答1:

You could use styles:

@grid.GetHtml(columns: grid.Columns(
    grid.Column("Name", "Name", canSort: true, style: "name"),
    grid.Column("Address", "Address", canSort: true, style: "address")
));

and in your CSS file:

.name {
    width: 50px;
}

.address {
    width: 300px;
}


回答2:

To add to the good advice of Darin Dimitrov, would further recommend a convention (since CSS promotes reuse), try to use existing or common styles for often used elements (e.g., columns)--remember that you can apply multiple styles, separated by a space here, too--they will simply be merged into the resulting attribute.

@{
    var grid = new WebGrid(Model, canSort: true, canPage: true, rowsPerPage: 10);
    grid.Pager(WebGridPagerModes.NextPrevious);
    @grid.GetHtml(columns: grid.Columns(

    grid.Column("Name", "Name", canSort: true, style: "col-sm cssStyle2"),
    grid.Column("Address", "Address", canSort: true, style: "col-med address"),        
    //other columns
    ));

}

/*styles*/
.col-sm { width: 100px; min-width: 90px; }
.col-med { width: 150px; min-width: 120px; }  <--could be reused
.address { font-weight: bold; } <-- could be reused
.cssOther3 { font-weight: bold; }  <-- may not be as not as reusable
.cssStyle2 { text-align: right; }  

So, in other words, you're not stuck with a single style package a continue to have flexibility when applying "reuse".



回答3:

Only CSS

/*IE7+*/  
th:first-child  { width:30px; }  
th:first-child + th { width:30px; }  
th:first-child + th + th  { width:100px; }  
/*IE9 +*/  
th:nth-of-type(1) { width:30px; }  
th:nth-of-type(2) { width:30px; }  
th:nth-of-type(3) { width:100px; }  
th:nth-of-type(4) { width:200px; }  
th:nth-of-type(5) { width:40px; }