PreciseTech
PreciseTech

Reputation: 1

putting Store procedure columns in Razor code

i am calling store procedure from MVC, which returns single record only.

SP contains:

PROCEDURE [dbo].[GetMonthlyReport] @emplID INT = NULL,
    @month VARCHAR(50) = NULL
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    IF (@emplID IS NOT NULL AND @month IS NOT NULL) --If Block begins
    BEGIN
        SELECT *
        FROM MonthlyRecord
        WHERE Month = @month AND EmplID = @emplID
    END --If block ends
    ELSE --Else block begins
    BEGIN
        RETURN 0
    END --Else block ends
END

now it is selecting, empID, Overtime, Month, TotalDuration from MonthlyRecord View,

What i want to do is to put these fields in custom template e.g. HTML TABLE or List, like :

<table style="width:300px">
<tr>
<td>Employee ID</td>
<td>Month</td> 
</tr>
<tr>
<td>@empID</td>
<td>@Month</td> 
</tr>
</table>

something dynamic.

MVC Code:

Controller:

public ActionResult Generated_PaySlip(int? emplID, String month) 
{
IEnumerable<GetMonthlyReportResult> PaySlip = DataContext.GetMonthlyReport(emplID, month).ToList();
return View(PaySlip);
}

View:

@using EmployeeAttendance_app.Models

<h2>Employee Pay Slip</h2>

<table style="width:300px">
<tr>
<td>Employee ID</td>
<td>Month</td> 
</tr>
<tr>
<td>@empID</td>
<td>@Month</td> 
</tr>
</table>

Upvotes: 0

Views: 125

Answers (1)

jwatts1980
jwatts1980

Reputation: 7356

You are pretty close, but you need to tell the Razor view what model you're using. Revise your Razor code as such:

@model GetMonthlyReportResult
@using EmployeeAttendance_app.Models

<h2>Employee Pay Slip</h2>

<table style="width:300px">
<tr>
<td>Employee ID</td>
<td>Month</td> 
</tr>
<tr>
<td>@Model.empID</td>
<td>@Model.Month</td> 
</tr>
</table>

Then you can use Model as the variable in the Razor view to access the properties.

update

I just noticed that you're returning an IEnumerable. Somewhere you need to convert that into a single item. Since you are only expecting to see one return item, I think it would be easier to do that in the controller.

public ActionResult Generated_PaySlip(int? emplID, String month) 
{
    IEnumerable<GetMonthlyReportResult> PaySlip = DataContext.GetMonthlyReport(emplID, month).ToList();
    return View(PaySlip.FirstOrDefault());
}

update

You can leave the controller as is in your example and do it in the Razor view like so:

@model IEnumerable<GetMonthlyReportResult>
@using EmployeeAttendance_app.Models

@{
    var item = Model.FirstOrDefault();
}

<h2>Employee Pay Slip</h2>

<table style="width:300px">
<tr>
<td>Employee ID</td>
<td>Month</td> 
</tr>
<tr>
<td>@item.empID</td>
<td>@item.Month</td> 
</tr>
</table>

But again, since you're only expecting one item, there is no need to add that logic to the Razor view. Best, I think, to leave that kind of stuff to the controller whenever possible.

Upvotes: 1

Related Questions