0

I have a controller which I want it to return only two selected rows to a view. It looks like this:

public ActionResult Details(int sourceId, int targetId)
    {
        ConfigurationItem sourceItem = db.ConfigurationItemSet.Find(sourceId);
        ConfigurationItem targetItem = db.ConfigurationItemSet.Find(targetId);

        return View();
    }

What should I put in a "return"? I want to make a view with only two specific rows selected by Id from the table and put it in two separate grids.

1
  • If you are not using any Model then try using ViewBag Commented Jul 8, 2014 at 10:08

3 Answers 3

2

You should use a ViewModel (thats the recommended way in MVC).

The ViewModel

public class DetailsViewModel
{
    public ConfigurationItem TargetItem { get; set; }
    public ConfigurationItem SourceItem { get; set; }
}

The Action Method

public ActionResult Details(int sourceId, int targetId)
{
    var viewModel = new DetailsViewModel();
    viewModel.TargetItem  = db.ConfigurationItemSet.Find(targetId);
    viewModel.SourceItem = db.ConfigurationItemSet.Find(sourceId);
    return View(viewModel);
}

The View (Razor)

@model DetailsViewModel

// use Model.TargetItem  and Model.SourceItem 
Sign up to request clarification or add additional context in comments.

Comments

2

you can do it like

Action

public ActionResult Details(int sourceId, int targetId)
{
    var sourceItem  = new list<ConfigurationItem>(); 

    ConfigurationItem sourceItem1 = db.ConfigurationItemSet.Find(sourceId);
    ConfigurationItem targetItem2 = db.ConfigurationItemSet.Find(targetId);
    sourceItem.add(sourceItem1);
    sourceItem.add(sourceItem2);
    return View(sourceItem.AsEnumerable());
}

View

@model IEnumerable<ConfigurationItem>

Comments

1

If you are not using any Model then try using ViewBag.sourceItem to pass data from Controller to your View

ViewBag.sourceItem = db.ConfigurationItemSet.Find(sourceId);
ViewBag.targetItem = db.ConfigurationItemSet.Find(targetId);

2 Comments

This is correct. But it is not the "right" way to use a viewbag. I find them really unorganized and hard to keep track on. I would use a model with it.
@Izekid I mentioned if you are not using a model then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.