简体   繁体   中英

Webmatrix / Razor Getting Data out of SQL column with space in its name

I have a basic WebMatrix CSHTML page where I am querying a stored procedure that returns some data. Several of the columns have spaces in them. I cannot modify the column names (not my database). Also, since I am not doing SELECT FROM I cannot do AS New_Name on a column. So with this code that I have where I am getting a value from a specific row / column, how can I specify a column name with a space?

var db = Database.Open("MyDb");
var sql = @"EXEC myProcedure";
var result = db.Query(sql);
var header_value = result.ElementAt(0);
.
.
.
@header_value.ColumnName

Lets say the name of the column is 'Test Column' I tried

 @header_value.["Test Column"]

and

 @header_value["Test Column"]

and

 @header_value[Test Column]

None of this works. Is there any way to specify this column which has a space in my application without changing the column on the back end?

There are three ways to retrieve the value of a dynamic record column,

using the column index (eg @header_value[1] ),

using the column name (eg @header_value["Test Column"] ),

or using the column name as property (eg @header_value.columnName , but you can't use this method if the column name has spaces).

I don't know why the column name method doesn't work with you. Do you receive any error message?

Anyway, you could look at the column names of your dynamic record with a snippet like this:

<div>
    @foreach(var col in header_value.Columns){
        <p>@col</p>
    }
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM