How can I get data from MVC Control’s to CSHTML

I apologize in advance for my mistakes, as I am new to the forum and .net

I’m working on an application using asp.net, c #, mvc5, EF6, db first

My problem is
I want to use a sql statement return in cshtml on the controller side, I cannot access variables that occur after the query in cshtml;

Thank you in advance to helpers

Conroller: OFISController.cs;

public ActionResult Index2()
{       sql = "SELECT * FROM OFIS o "
              + "left join OFISFIRMABAGLA ofb on ofb.OFID = o.OFID "
              + "left join FIRMA f on f.FID = ofb.FID";
    var qOFIS = db.Database.SqlQuery<DbSet>(sql);
    if (qOFIS == null) HttpNotFound();
   
   return View(qOFIS.ToList());

}

View: Index2.cshml;

@model IEnumerable<ildemavm3.Controllers.OFISsController>

...

<td>@Html.DisplayFor(modelItem => item.??????  )</td>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

First create Model class for return result as per Query:
Example:

namespace ildemavm3.Models
{
    public class SampleData
    {
        public string Name {get; set;}
        public string Address{get; set;}
    }
}

Please note select Query must have same property name as Model class above

Controller: OFISController.cs;

public ActionResult Index2()
{
    sql = "SELECT **Name,Address** FROM OFIS o "
              + "left join OFISFIRMABAGLA ofb on ofb.OFID = o.OFID "
              + "left join FIRMA f on f.FID = ofb.FID";
    var qOFIS = db.Database.SqlQuery<SampleData>(sql);
    if (qOFIS == null) HttpNotFound();
   
    return View(qOFIS.ToList());

}

var qOFIS = db.Database.SqlQuery<SampleData>(sql);

Update Model class as above here I have created SampleData model class in starting

Change View: Index2.cshml as below;

@model IEnumerable<**ildemavm3.Models.SampleData**>
...
<td>@Html.DisplayFor(modelItem => item.**Name** )</td>

Method 2

There are many ways to pass data from MVC controller to the view. You can use viewData or viewBag which is a very handy and flexible option. You can pass multiple data at a time using this approach.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x