ddess
ddess

Reputation: 13

ASP.NET MVC view calculate for a column

I have a view model, I have a list from a table in my view model, I'm binding the model to my view and bind the list to an html table.

View model:

public IEnumerable<MyTable> TableObject { get; set; }

View:

@if (Model.TableObject != null)
{
        foreach(var item in Model.TableObject)
        {
            <td>@item.Column1</td> 
            <td>@item.Column2</td>
            <td>CalculatedVariable</td>
        }   
}

I can get all of my table column values like Column1, Colum2. But I want to calculate a value for display. I can get this value in the controller with a method like this:

Controller:

public string GetCalculateValue(List<MyTable> searchList, int compareValue)
{
    string returnValue = String.Empty;

    var _theList = searchList.Where(x => x.myValue == compareValue).ToList();

    if (_theList.Count() > 1)
    {
        returnValue = "OK";
    }

    return returnValue;
}

I want to bind that returnValue to my view for display in a column in the html table. How can I pass this string value for my table rows? I hope I could explain.

Thanks for help.

Upvotes: 1

Views: 279

Answers (1)

Dave Barnett
Dave Barnett

Reputation: 2216

Its hard to see what's going on but I believe your general approach needs to be as follows. Add a property to your MyTable class so that it looks like this

public class MyTable
{
    public string Column1 {get; set;}
    public string Column2 {get; set;}
    public int myValue {get; set;}
    public string CalculatedVariable {get; set;}
}

Then foreach MyTable object that you have set the value of CalculatedVariable in the controller. Then you will be able to display Calculated variable like your other properties.

Not what you asked but I think your GetCalculateValue can be made more readable if it is changed to this.

public string GetCalculateValue(List<MyTable> searchList, int compareValue)
{
    return searchList.Any(x => x.myValue == compareValue) ? "OK" : "";          
}

Upvotes: 1

Related Questions