0

I can't find any updated answers that work with Visual Studio 2017. I've been stuck for over a day trying to figure it out and every guide I find online is either extremely dated or anything that I try to apply to my code give me errors I can't fix. I am using C#, HTML5, ASP.NET MVC5, and VS2017

First off I have my controller which connects to the SQL Server database with:

public void GetStoredProc()
{
    Exclusion objExclusion = new Exclusion();

    string StrConnectionString = ConfigurationManager.ConnectionStrings["EligibilityContext"].ConnectionString;

    SqlConnection sqlConnection1 = new SqlConnection(StrConnectionString);

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "[advantage].[GetAdvantageEligibilityDataOverride]";
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();

    SqlDataReader reader = cmd.ExecuteReader();

    if (reader.HasRows)
    {
        int count = reader.FieldCount;

        while (reader.Read())
        {
            if (count > 3)
            {
                int IntNum;
                int.TryParse(reader.GetValue(0).ToString(), out IntNum);
                objExclusion.PolicyNo = IntNum;
                objExclusion.PolicyMod = (reader.GetValue(1).ToString());
                objExclusion.InsuredName = (reader.GetValue(2).ToString());
                objExclusion.ClientID = IntNum;                   
                //Console.WriteLine(reader.GetValue(i));
            }
        }
    }

    // Data is accessible through the DataReader object here.
    sqlConnection1.Close();
}

Here is my index.html page. I know there needs to be code added here in order to display the web page but I'm a programming noob and am at a loss for what exactly to put.

@model IEnumerable<Advantage_Exclusions_Eligibility.Models.Exclusion>

@{
ViewBag.Title = "Index";
}

<h2>AEE List</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<p>
&nbsp;</p>

<div>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.PolicyNo)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.PolicyMod)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.InsuredName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.ClientID)
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.PolicyNo)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.PolicyMod)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.InsuredName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.ClientID)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.PolicyNo }) |
        @Html.ActionLink("Details", "Details", new { id=item.PolicyNo }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.PolicyNo })
    </td>
</tr>
}
</table>
    <div class="pagination">
        <nav id="AEEPagination" aria-label="Page navigation" 
style="display:none;">
            <ul class="pagination pagination-sm"></ul>
        </nav>
    </div>
</div>

Any and all help would be greatly appreciated!

Nate Jenson
  • 2,664
  • 1
  • 25
  • 34
Roshaan Khan
  • 3
  • 1
  • 5
  • 1
    The version of Visual Studio has nothing to do with what code you can write, so that's not a good excuse for excluding solutions. – Heretic Monkey Jul 26 '17 at 16:30
  • @MikeMcCaughan I know that normally that doesn't make a difference. But most solutions I found were from 2012 or older versions and I kept getting errors trying to duplicate it. Maybe it wasn't there version difference and perhaps just the way the codes formatted. But I've been unable to find an effective solution none the less. – Roshaan Khan Jul 26 '17 at 16:38
  • What exactly is your problem statement? Are you facing problem to display the data in View or something else? – Siva Gopal Jul 26 '17 at 16:50
  • @SivaGopal How to display the data in View is the main problem. My research showed the using GridView is the best option since my data is going to be changing often. But I can't get any example GridView code to work for me. – Roshaan Khan Jul 26 '17 at 16:52

3 Answers3

1

Your method public void GetStoredProc() will either need to return a model @model IEnumerable<Advantage_Exclusions_Eligibility.Models.Exclusion> or take one in as an argument and populate the model with the result from your stored procedure.

An abbreviated example might look like this:

// Your url, eg. /<controller>/exclusions
public ActionResult Exclusions()
{
    var viewmodel = GetStoredProc();

    // pass your IEnumerable<Exclusion> to the view
    return View(viewmodel);
}

// Note the return type
public IEnumerable<Exclusion> GetStoredProc()
{
    var exclusions = new List<Exclusion>();


    // ... ...

    if (reader.HasRows)
    {
        int count = reader.FieldCount;

        while (reader.Read())
        {
            Exclusion objExclusion = new Exclusion(); // create a new exclusion for each row!
            if (count > 3)
            {
                int IntNum;
                int.TryParse(reader.GetValue(0).ToString(), out IntNum);
                objExclusion.PolicyNo = IntNum;
                objExclusion.PolicyMod = (reader.GetValue(1).ToString());
                objExclusion.InsuredName = (reader.GetValue(2).ToString());
                objExclusion.ClientID = IntNum;                   
                exclusions.Add(objExclusion); // add the exclusion to your result set!
            }
        }
    }

    // Data is accessible through the DataReader object here.
    sqlConnection1.Close();

    return exclusions;
}

In your view, you'll also need to make some tweaks. In this context your model is an IEnumerable of models, and therefore there is no model.PolicyNo, model.PolicyMod, etc.like is being used in the table header. Assuming your Exclusion model class already has the display name properties set, you can just change the header of your table to use those properties of the first Exclusion model in the collection.

<th>
    @Html.DisplayNameFor(model => model.First().PolicyNo)
</th>
<th>
    @Html.DisplayNameFor(model => model.First().PolicyMod)
</th>
<th>
    @Html.DisplayNameFor(model => model.First().InsuredName)
</th>
<th>
    @Html.DisplayNameFor(model => model.First().ClientID)
</th>
<th></th>

I'd also recommend putting some checks around the table to make sure there's data to show:

@if (model.Any()) {
    // Show the table
     <th>
        @Html.DisplayNameFor(model => model.First().PolicyNo)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.First().PolicyMod)
    </th>
    // ... 
}

A side note, it's good practice to wrap SQL connections in a using. I grabbed the first explanation I could find here. You can even chain your SqlCommand and SqlConnection usings together:

eg.

using (var conn = new SqlConnection(connectionString)) 
using (var cmd = new SqlCommand())
{
    // Use conn and cmd here.
}
Nate Jenson
  • 2,664
  • 1
  • 25
  • 34
  • Hello @njenson ! Thank you for your response. I think it helped me get on the right track. However, after I added the IEnumerable and all it's code I'm getting one error under the "GetStoredProc()". It says not all code paths are used. How exactly can I go about using applying it? Because the application still won't display anything without HTML code right? – Roshaan Khan Jul 26 '17 at 17:24
  • @RoshaanKhan it sounds like you're missing the `return exclusions;` statement at the end of `GetStoredProc()` – Nate Jenson Jul 26 '17 at 17:28
  • So I added everything you said and there's still a couple errors even though I do have the "return exclusions;" that's one of the errors. So besides the "GetStoredProc()" saying not all code paths are used. Theres another error underline at the return keyword saying "ExclusionsController.GetStoredProc() returns void, a return keyword must not be followed by an object expression. I also have a couple warning regarding some problems with the HTML but I think I can fix that once this is solved. – Roshaan Khan Jul 26 '17 at 17:36
  • Look at the code I posted carefully. The error message states that the method returns void. You'll see in my answer that GetStoredProc() must now return the type of model your view is expecting, eg. `public IEnumerable GetStoredProc()` instead of `public void GetStoredProc()` – Nate Jenson Jul 26 '17 at 17:38
  • Ohhh okay I had some confusion with the way it was ordered that was my fault. So I've totally debugged my controller, now my application is breaking at the HTML. It first wouldn't allow the "@if (model.Any()) {" so I removed it just to try and get the app to work. Now it's breaking at the model[0] with the error claiming [] cant be used with type IEnumerable. – Roshaan Khan Jul 26 '17 at 17:49
  • That fixed some things. Now the page actually runs though. However the only data that showed up was a 0 (zero) under the policy number header and client id header. There was no data under the middle two headers. The zeroes that appeared are incorrect and not the data the stored procedure is calling. Also at the very top of the HTML page i wrote "@model IEnumerable" and the entire phrase inside the <> is underlined with the error Validation (html5): Element <> is not supported. I greatly appreciate your help so far!!! – Roshaan Khan Jul 26 '17 at 18:10
  • Have you tried searching these errors to try and resolve them? I'm afraid I can't help any further at this point. – Nate Jenson Jul 26 '17 at 18:37
  • Yes I did, couldn't find anything regarding this situation. I'll figure it out though. Thanks for all your help regardless. It really helped me move in the right direction – Roshaan Khan Jul 26 '17 at 18:52
0

I worked with the similar kind of code earlier. First create an action in the Controller. Then run the stored procedure using ADO.net. You can pass parameters to your stored procedure using SqlParameter[].

Controller code:

public ActionResult MyResult()
{
    string userid = User.Identity.GetUserId();
    string constr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("My_Result", conn))
        {
            conn.Open();
            cmd.CommandType = CommandType.StoredProcedure;

            DataSet ds = new DataSet();
            SqlParameter[] prms = new SqlParameter[1];
            prms[0] = new SqlParameter("@Userid", SqlDbType.VarChar, 500);
            prms[0].Value = userid;
            cmd.Parameters.AddRange(prms);
            SqlDataAdapter ad = new SqlDataAdapter(cmd);
            ad.Fill(ds);

            conn.Close();

            return View(ds);
        }
    }
}

With this you stored all the records retrieved from stored procedure into a DataSet. Now return view along with the dataset data.

Now in the View, You need to display these records into a table.

View Code

@using System.Data
@model DataSet

@{
    ViewBag.Title = "MyResult";
}

<h2 style="text-align:center;">Result History</h2>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <style>
        table{
            width:75%;
            text-align:center;
        }
        th,td,tr{
            border:1px solid black;
            text-align:center;
            padding:20px;
        }
    </style>

</head>
<body>
    <table>
        <tr>

            <th>UserName</th>
            <th>ExamDate</th>
            <th>Score</th>
        </tr>
        @foreach (DataRow row in Model.Tables[0].Rows)
        {
            <tr>

                <td>@row["UserName"]</td>
                <td>@row["ExamDate"]</td>
                <td>@row["Score"]</td>
            </tr>
        }
    </table>
</body>
</html>

Now all the data that is retrieved from stored procedure will be displayed into the table in View.

Output: Data displayed in a table

TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
Dinesh
  • 1
  • 1
0

We can also simplify the view in the following way..!

   @using System.Data;
   @model DataSet
   <center>
   <h2>Result History</h2>
   <table class="table table-bordered table-responsive table-hover">
        <tr>
            <th>UserName</th>
            <th>ExamDate</th>
            <th>Result</th>
        </tr>
    @foreach(DataRow d in Model.Tables[0].Rows)
    {
   <tr>
    <td>@d["UserName"]</td>
    <td>@d["ExamDate"]</td>
    <td>@d["Result"]</td>
   </tr>
 }
 </table>
</center>`

The Output

Jérôme
  • 1,254
  • 2
  • 20
  • 25
BhanuTeja
  • 1
  • 1