Cast List<ViewModel> to ViewModel? - asp.net-mvc

I want to preface this by saying I am new to working with models. Please forgive me if this question has a simple answer.
I have been struggling to revert a listed view model back to view model. To give some background, I have a search form being passed to a model coming from my ActionResult and am then getting a filter out the results.
[ Controller ]
public ActionResult GetFilters(MembershipVM model)
{
var uDataList = new List<MembershipVM>();
model = _service.GetFilters(model);
return View("SendEmail", model);
}
[ Service ]
public List<MembershipVM> GetFilters(MembershipVM model)
{
var query = _context.Members.Where(f => f.Deleted == 0).AsQueryable();
var members = _context.Members.ToList();
query = query.Where(f => agencyTypes.Contains(f.AgencyType));
var uDataList = new List<MembershipVM>();
foreach (var member in members)
{
var uData = new MembershipVM();
uData.Email = member.Email;
uData.AgencyType = member.AgencyType;
...
uDataList.Add(uData);
}
return uDataList;
}
How can I cast the List from "_service.GetFilters" to MembershipVM? Is there a better/easier way to get the results as an object from the "_service.GetFilters" service?
Thanks so much in advance!
Daisy

I am not sure what you are trying to do here. First you get the results of your filter from this code:
model = _service.GetFilters(model);
And the definition of your method is this:
public List<MembershipVM> GetFilters(MembershipVM model)
So you would expect that this is a list of results. In short, a collection of results.
Now if you want to pass it on your ActionResult as one entity only, then getting one of your results will do the trick:
return View("SendEmail", model.Take(1).SingleOrDefault());
But why do you need to pass one entity only? But that should work with your current requirement.

Related

Passing SItecore Item ID to Model from Controller

I am creating products from a product template. Each time a customer selects a product to view information about, the data from that product needs to get loaded. I have created a controller, model and view. The model is generated with TDS. I need to pass the item id to the [SitecoreId] from the controller. Here is the code I am using:
From the layout:
#{var id = Sitecore.Data.ID.Parse("{74A67488-8E33-47E2-86F5-25AD23FDF3D3}"); }
#Html.Sitecore().ControllerRendering("ProductOverview", "Index", new { ItemId = #id })
The controller:
public class ProductOverviewController : Controller
{
private readonly IMvcContext _mvcContext;
public ProductOverviewController(IMvcContext mvcContext)
{
_mvcContext = mvcContext;
}
// GET: ProductOverview
public ActionResult Index()
{
var itemId = string.Empty;
var rc = RenderingContext.CurrentOrNull;
if (rc != null)
{
var parms = rc.Rendering.Properties;
itemId = parms["ItemId"];
}
var dataSource = _mvcContext.GetContextItem<ProductOverviewModel> ();
return View(dataSource);
}
}
The itemId var has the correct id that I am passing from the layout (hard coded for now). From here I am at an absolute loss on how to get that into the model. I have tried dozens of suggestions from searches but the model always uses the current item (as set by GlassBase in the model itself) as opposed to the product id that contains the data for that product.
Is what I want to do even possible? Can the [SitecoreId] even be overridden?
The line where you are setting the value for dataSource using Glass Mapper is where you'll want to make your change..
Glass Mapper lets you use a number of different options to get the Item and cast to your "type" which looks to be ProductOverviewModel currently.
you can use the following for example (notice that I've used .SitecoreService.GetItem instead of .GetContextItem ):
//pass the GUID into here (you'd need to cast to a Guid first instead of ID)
var dataSource = _mvcContext.SitecoreService.GetItem<ProductOverviewModel>(guid);
//or if you wanted to get your ID as a Sitecore Item you could use
var dataSource = _mvcContext.SitecoreService.GetItem<ProductOverviewModel>(item.Paths.Path);

mvcmusicstore v3.0 (storeDB does not exist in the current context)

It's my first dealing with mvc and I am going with a tutorial from this link https://archive.codeplex.com/?p=mvcmusicstore . I have all steps done but when I write:
public ActionResult Index()
{
var genres = storeDB.Genres.ToList();
return View(genres);
}
it says storeDB does not exist in the current context. Why am I getting this message?
Please help in that
In your context you have DBSet<Genre> Genre (not plural)
Within you controller you have - (Genres plural)
var genres = storeDB.Genres.ToList();
So you could change to -
var genres = storeDB.Genre.ToList();
Do you have this field declared in your controller?
MusicStoreEntities storeDB = new MusicStoreEntities();

Getting error when multiple results passing to view in asp.net MVC5

I use asp.net mvc 5 and EF 6 .I have following code in my controller
var resultOne = stats.GetPlayerStatsByParam(year, modeOne); //first
ViewData["more"] = stats.GetTeamStatsID(year); //second
return View("StatsNew", resultOne.ToList());
I am able to display result in view using "resultOne". Now I want to pass another data to same view using ViewData[]. its a stored procedure and the result is paasing to "ViewData["more"]".
I have done following code for "ViewData["more"]" in View page
But I am getting an error saying that 'object reference not set'
#foreach (var item in ViewData["more"] as #List<demo.GetTeamStatsID_Result>)
{
#item.Pld;
}
Use a viewmodel and extend it by the data coming from stats.GetTeamStatsID(year);
Do not use ViewBag or ViewData if not necessary for some reason (which I canĀ“t imagine right now)
As the comments have already pointed out, build a ViewModel class, that wraps everthing you need:
//I am using fake types here, sinceI don't know your model classes
//substitute accordingly!
public class MyViewModel
{
public PlayerStatsType PlayerStats { get; set;}
public List<demo.GetTeamStatsID_Result> Teams { get; set;}
}
Then in your action method:
var vm = new MyViewModel();
vm.PlayerStats = stats.GetPlayerStatsByParam(year, modeOne); //first
vm.TeamId = stats.GetTeamStatsID(year); //second
return View("StatsNew", vm);
Amend the model declaration in your view:
#model Namespace.Models.MyViewModel //again use namespace for your vm class
Now you can access both properties from your model:
#foreach (var item in Model.Teams)
{
#item.Pld;
}

ASP.NET MVC 5 API, Changing a class in GET function

I'm working on a dotnet mvc5 application. Here's a function from my api of customer controller
public IHttpActionResult GetCustomers()
{
var customerDtos = _context.Customers.ToList().Select(Mapper.Map<Customer, CustomerDto>);
return Ok(customerDtos);
}
I need to add "TYPEAHEAD" plugin to my application. The video series/instructor I'm following says to make the function code change to
public IHttpActionResult GetCustomers(string query = null)
{
var customersQuery = _context.Customers
.Include(c => c.MembershipType);
if (!String.IsNullOrWhiteSpace(query))
customersQuery = customersQuery.Where(c => c.Name.Contains(query));
var customerDtos = customersQuery
.ToList()
.Select(Mapper.Map<Customer, CustomerDto>);
return Ok(customerDtos);
}
in order to make "TypeAhead" plug in work on my view.
The only problem is previously while creating customers I didn't feel the need to add "MembershipType" class to my customer. So how do I use the new code without MembershipType. Is there any other attribute I can replace it with? Name, ID etc.
.Include(c => c.MembershipType);
essentially means that you also want to include the 'child' collection of MembershipType
See here for more information on Loading Related Entities
For your case, you can simply omit this.
public IHttpActionResult GetCustomers(string query = null)
{
var customersQuery = _context.Customers;
if (!String.IsNullOrWhiteSpace(query))
customersQuery = customersQuery.Where(c => c.Name.Contains(query));
var customerDtos = customersQuery
.ToList()
.Select(Mapper.Map<Customer, CustomerDto>);
return Ok(customerDtos);
}
You don't need to replace it with anything.
customersQuery is then an IQueryable<Customer> which the rest of this code can append Where clause to.
It is not executed against the database until the ToList call.

Render different view depending on the type of the data (asp.net MVC)

So lets suppose we have an action in a controller that looks a bit like this:
public ViewResult SomeAction(int id)
{
var data = _someService.GetData(id);
...
//create new view model based on the data here
return View(viewModel);
}
What I m trying to figure out is the best way to render a diferent view based on the type fo the data.
the "_someService.GetData method returns an data that knows its out type (ie not only you can do typeof(data) but also you can do data.DataType and you ll get an enum value
so I could achieve what I m trying to do doing something kinda like this
public ViewResult SomeAction(int id)
{
var data = _someService.GetData(id);
//mapping fields to the viewModel here
var viewModel = GetViewModel(data);
swtich(data.DataType)
case DataType.TypeOne: return View("TypeOne", viewModel); break;
...
}
But this does not seem to be the nicest way, (I dont event know if it would work)
Is this the way to go?
Should I use some sort of RenderPartial Aproach? after all , waht will change in the view is mostly the order of the data (ie the rest of the view would be quite similar)
Cheers
Try this:
public ViewResult SomeAction(int id)
{
var data = _someService.GetData(id);
var viewModel = GetViewModel(data);
return View(data.GetType().Name, viewModel);
}
Then just name your views accordingly.

Resources