0

I have another problem wherein I have a method in controller that gets a certain data and place it to the view.

Controller

public ActionResult Index()
{
        var data = (from p in db.eTransactions
                    orderby p.id descending
                    select p.id).Take(1);
        ViewBag.id = data;
        return View();
}

View

<input type="text" value="@(ViewBag.id)"/>

instead of the data(which is a certain value) I want to get, the data thrown is like a command in an sql server

SELECT TOP (1)     [Extent1].[id] AS [id]    FROM [dbo].[eTransaction] AS [Extent1]    ORDER BY [Extent1].[id] DESC

What is needed to do to fix this?

  • Try changing `Take(1)` with `Single()` or `First()`. `ViewBag.id` should contain a single scalar value. – Tetsuya Yamamoto Nov 14 '17 at 04:09
  • Your query returns a collection (even though it contains only one item). But its terrible practice to use `ViewBag` - pass a model to your view and strongly bind to it using `@Html.TextBoxFor(m => m.yourProperty)` –  Nov 14 '17 at 04:18
  • can i pass a model to view even if it came from a different class? the value getting taken here is different from the model in the view. – marvin castro Nov 14 '17 at 05:08
  • You can use ViewBag.id = db.eTransactions.OrderByDescending(x => x.id).Select(x=>x.id).FirstOrDefault(); – Asif Raza Nov 14 '17 at 05:20
  • Your editing data so ALWAYS use a view model (which will contain all the properties you need in the view - [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Nov 14 '17 at 05:26
  • ok the thing that fixed it was adding FirstOrDefault() after the Take(1). see answer below or just use @AsifRaza code. Both of them worked like a charm – marvin castro Nov 14 '17 at 05:43
  • @marvin castro Thank U , Glad i helped u. – Asif Raza Nov 14 '17 at 10:07

1 Answers1

0

ok the thing that fixed it was adding FirstOrDefault() after the Take(1).

public ActionResult Index()
{
    var data = (from p in db.eTransactions
                orderby p.id descending
                select p.id).Take(1).FirstOrDefault();
    ViewBag.id = data;
    return View();
}