There is always something with MVC... has any one every run into this error?
This is the error I am getting
cannot implicitly convert type 'system.web.mvc.viewresult' to 'system.action
What I am trying to do is return a list using a viewmodel of a single table.I am hoping this will help me understand view models.
I want this table to be a function in the control that I can call any time I need it so that I can list the jobs using the view model list.
I hope this is clear.
public Action ListJobPostings()
{
List<Jobs_ViewModel_Class> ListOfJobsViewModelList = new List<Jobs_ViewModel_Class>();
var ListOfJobs = (from JobPost in db.JOBS_POST_TBL select new { JobPost.POSIT_CLOSING_DATE, JobPost.POSIT_POSTING_DATE, JobPost.POSIT_NUMBER, JobPost.POSIT_DESCRIPTION, JobPost.POSIT_JOB_URL }).ToList();
return ListOfJobsViewModelList;
}
This is the view model thing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace JobsOpeningBackendSite.VIEW_MODELS
{
public class Jobs_ViewModel_Class
{
[DisplayName("Job Posting Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public System.DateTime POSIT_POSTING_DATE { get; set; }
[DisplayName("Job Closing Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public System.DateTime POSIT_CLOSING_DATE { get; set; }
[DisplayName("Position Number")]
public short POSIT_NUMBER { get; set; }
[DisplayName("Position Discription")]
public string POSIT_DESCRIPTION { get; set; }
[DisplayName("Job Link URL")]
public Nullable<bool> POSIT_JOB_URL { get; set; }
}
}
This is the tutorial and my source looks similar but I am getting this wacky error any ideas?
you declared a function to return an an object of type "Action", but are trying to return an object of type "List<Jobs_ViewModel_Class>". C# is type safe meaning its a syntax error assign object of the wrong type.
when you tried return View(...), it also is not of type "Action", but rather "ViewResult", which inherits from "ActionResult". again a type mismatch.
note: "Action" is generic type that defines a type that is a delegate with no parameters and returns type void.
This is the tutorial and my source looks similar but I am getting this wacky error any ideas?
cannot implicitly convert type 'system.web.mvc.viewresult' to 'system.action
What's wacky about it? It's a basic lack of understanding OO principles.
You cannot tell viewresult, a class/type that it's going to be an
action another class/type. You can't tell a car object that it's going to be jet object.
How is a List<T> of Jobs_ViewModel_Class objects in a collection ever going to be an
Action?
How can you take an ListOfJobs anaymous types result being returned in a Linq projection and make it be a known type of Jobs_ViewModel_Class in a collection a List<T>?
If not that the code blew up with the exception you got, it would have returned nothing out of the method, becuase the projection used anaymous type instead of a projection being projected using a custom type of Jobs_ViewModel_Class is never done.
The type of return must be the same as the type of the method or have an inheritance relationship. Here, if you just want to get the list you can change
Action to List<Jobs_ViewModel_Class>. If you want to return a view, you should change it to
ActionResult.
Best Regards,
Jiadong Meng
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Yes the type was on my part but the tutorial has some other issues and I found a better one.
But Let me ask you all this... I am trying to display my a view model in a detail view vs the table that it returns by default when the wizard builds it.
As I stated before I don;t understand view models very well and all of the reading and tutorial over the years of trying to get a better grasp of it...I just don;t get so I am trying to write myself a small source code example that makes sense to me that
I can reference that way I will be able to use them if I make my source codes follow the same pattern each time.
THis is what I have
// GET: JOBS_POST_TBL/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//Replace With View Model
//JOBS_POST_TBL jOBS_POST_TBL = db.JOBS_POST_TBL.Find(id);
Jobs_ViewModel_Class JobDetails = db.JOBS_POST_TBL.FirstOrDefault(j => j.POSIT_NUMBER == id);
if (jOBS_POST_TBL == null)
{
return HttpNotFound();
}
return View(jOBS_POST_TBL);
}
But I am getting an error : Cannot implicitly convert type 'JobsOpeningBackendSite.JOBS_POST_TBL' to 'JobsOpeningBackendSite.VIEW_MODELS.Jobs_ViewModel_Class
What is odd in a system that I wrote 3 years about this type of thing worked but Instead of a sql table I created a sql view.
Is that some thing that I have to do here instead of using the table?
In my current production application I have this. which is the same thing that I am trying to do now...
// GET: XXX_XXXX/Details/5
[HandleError]
public ActionResult Details(int id)
{
//ViewBag.XXXXXX = new SelectList(GetXXXXList(), "Value", "Text");
try
{
//if (id == null) //Changed 01062020
if (id < 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//XXX_XXXX some_Thing = db.SOME_THING.Find(id);
//SEE: http://stackoverflow.com/questions/27150575/the-number-of-primary-key-values-passed-must-match-number-of-primary-key-values
VUE_SQL_VIEW_DETAILS_FULL some_THING = db.SOME_THING_DETAILS_FULL.FirstOrDefault(r => r.RES_REQ_ID == id);
if (some_Thing == null)
{
return HttpNotFound();
}
So I am not sure what I am doing wrong now??
Do you use the view model in the controller or do I just use them i the view
I need to ask a few clarifying questions as the code is a bit confusing. Is the controller named JOBS_POST_TBL? Can you provide the source for both the Jobs_ViewModel_Class and jOBS_POST_TBL class?
Actually I have a better idea. Create a test project to play with View models and whatever else you like. I recommend going through the standard Getting started with MVC and EF 6 tutorial. That will give us (you and the community) a common baseline project.
Sure... My goal here is to replace all the places where the wizard used the the Sql Table JOBS_POST_TBL with the view model:
The control is name JOB_POST_TBLController
So I made the view model and the error stated it needed to be something called enumerated so I made it to that. (yes the concept of enumeration has haunted me for a long time so I just found an example and made it so as I don't know what they mean by enumeration
when it comes to programming even thought I have read about ... there is no basic plain English definition on it's meaning as it is all so technical... but if it means that it needs to be countable (If it does mean it needs to be countable why don;t they just
say that vs some long technical meaningless word?) then that is what I did I think because it works for the Index view using a view model.
But I think that enumeration requirement has caused the view model to not be compatible with other other views... sadly.
But here is what I have
View Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace JobsOpeningBackendSite.VIEW_MODELS
{
public class Jobs_ViewModel_Class
{
[Key]
[DisplayName("Position Number")]
public short POSIT_NUMBER { get; set; }
[DisplayName("Job Posting Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public System.DateTime POSIT_POSTING_DATE { get; set; }
[DisplayName("Job Closing Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public System.DateTime POSIT_CLOSING_DATE { get; set; }
[DisplayName("Position Discription")]
public string POSIT_DESCRIPTION { get; set; }
[DisplayName("Job Link URL")]
public string POSIT_JOB_URL { get; set; }
}
//See: https://stackoverflow.com/questions/33044606/pass-ienumerable-viewmodel-to-view
//See: https://stackoverflow.com/questions/21694691/the-model-item-passed-into-the-dictionary-is-of-type-system-collections-generic
//See: http://techfunda.com/howto/262/list-data-using-viewmodel
public class JobsIenumViewModel
{
public IEnumerable<JobsIenumViewModel> jobs_ViewModel_Class { get; set; }
}
}
Controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using JobsOpeningBackendSite;
using JobsOpeningBackendSite.VIEW_MODELS;
namespace JobsOpeningBackendSite.Controllers
{
public class JOBS_POST_TBLController : Controller
{
private XXXX_UTILITIES_DBEntities db = new XXXX_UTILITIES_DBEntities();
//Set Up For View Model Use
List<Jobs_ViewModel_Class> ListOfJobsViewModelList = new List<Jobs_ViewModel_Class>();
// GET: JOBS_POST_TBL
public ActionResult Index()
{
//var ListOfJobs = (from JobPost in db.JOBS_POST_TBL select new { JobPost.POSIT_CLOSING_DATE, JobPost.POSIT_POSTING_DATE, JobPost.POSIT_NUMBER, JobPost.POSIT_DESCRIPTION, JobPost.POSIT_JOB_URL }).ToList();
//Using View Model vs the Table
var ListOfJobs = db.JOBS_POST_TBL.Include("JOBS_POST_TBL").Select(j => new Jobs_ViewModel_Class { POSIT_CLOSING_DATE = j.POSIT_CLOSING_DATE, POSIT_POSTING_DATE = j.POSIT_POSTING_DATE, POSIT_NUMBER = j.POSIT_NUMBER, POSIT_DESCRIPTION = j.POSIT_DESCRIPTION, POSIT_JOB_URL = j.POSIT_JOB_URL });
return View(ListOfJobs);
//return View(db.JOBS_POST_TBL.ToList());
}
// GET: JOBS_POST_TBL/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//JOBS_POST_TBL jOBS_POST_TBL = db.JOBS_POST_TBL.Find(id);
var ListOfJobs = db.JOBS_POST_TBL.Include("JOBS_POST_TBL").Select(j => new Jobs_ViewModel_Class { POSIT_CLOSING_DATE = j.POSIT_CLOSING_DATE, POSIT_POSTING_DATE = j.POSIT_POSTING_DATE, POSIT_NUMBER = j.POSIT_NUMBER, POSIT_DESCRIPTION = j.POSIT_DESCRIPTION, POSIT_JOB_URL = j.POSIT_JOB_URL });
Jobs_ViewModel_Class jOBS_POST_TBL = ListOfJobs.FirstOrDefault(j =>j.POSIT_NUMBER == id);
if (jOBS_POST_TBL == null)
{
return HttpNotFound();
}
return View(jOBS_POST_TBL);
}
// GET: JOBS_POST_TBL/Create
public ActionResult Create()
{
return View();
}
// POST: JOBS_POST_TBL/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PRID,POSIT_POSTING_DATE,POSIT_CLOSING_DATE,POSIT_NUMBER,POSIT_DESCRIPTION,POSIT_POST_STATUS")] JOBS_POST_TBL jOBS_POST_TBL)
{
if (ModelState.IsValid)
{
db.JOBS_POST_TBL.Add(jOBS_POST_TBL);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(jOBS_POST_TBL);
}
// GET: JOBS_POST_TBL/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
JOBS_POST_TBL jOBS_POST_TBL = db.JOBS_POST_TBL.Find(id);
if (jOBS_POST_TBL == null)
{
return HttpNotFound();
}
return View(jOBS_POST_TBL);
}
// POST: JOBS_POST_TBL/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PRID,POSIT_POSTING_DATE,POSIT_CLOSING_DATE,POSIT_NUMBER,POSIT_DESCRIPTION,POSIT_POST_STATUS")] JOBS_POST_TBL jOBS_POST_TBL)
{
if (ModelState.IsValid)
{
db.Entry(jOBS_POST_TBL).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(jOBS_POST_TBL);
}
// GET: JOBS_POST_TBL/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
JOBS_POST_TBL jOBS_POST_TBL = db.JOBS_POST_TBL.Find(id);
if (jOBS_POST_TBL == null)
{
return HttpNotFound();
}
return View(jOBS_POST_TBL);
}
public ActionResult ListJobPostings()
{
List<Jobs_ViewModel_Class> ListOfJobsViewModelList = new List<Jobs_ViewModel_Class>();
var ListOfJobs = (from JobPost in db.JOBS_POST_TBL select new { JobPost.POSIT_CLOSING_DATE, JobPost.POSIT_POSTING_DATE, JobPost.POSIT_NUMBER, JobPost.POSIT_DESCRIPTION, JobPost.POSIT_JOB_URL }).ToList();
return View(ListOfJobsViewModelList);
}
// POST: JOBS_POST_TBL/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
JOBS_POST_TBL jOBS_POST_TBL = db.JOBS_POST_TBL.Find(id);
db.JOBS_POST_TBL.Remove(jOBS_POST_TBL);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Index View That works with the enumerated View Model
if you're going to use a strongly typed language like C#, you should learn what types are. a bag (list) of oranges is not the same as an individual orange.
also you should run the EF queries in the controller via .ToList(), rather than in the view. EF queries are run every time your code iterates the query (foreach). .First() is hardly to get the first element. .Single() is hardly when there should only be
one.
Not sure what you mean and how that addresses or even helps with the question.
Its not about what I should do... it what I know how to do. I don;t really care about best practices as there is no such thing.
The best practice is what allows you to get a working program out the door and working well for your operation.
Is it the tightest who knows... All that "you should stuff" you need to tell that to microsoft as all I did was click on new mvc project and this is what that
option built using the visual studio wizard.
As for the I should use types... for the last 3 years of me finding this site and asking for help with some very hard to understand concepts ... that has been a constant refrain of yours... Sorry bruce it's not going to happen. All of the tutorials that
I have found show the patterns that I ended up using... they USE VAR.... I USE VAR done and dusted... if they don;t type I don't type.
Maybe you should report them to the type police but get off my back about that please... typing will not help me and if they programming tools does not require it,, then its not going to happen as it will just adds to the confusion for me as it adds a layer
of complication to a very hard concept to follow already.
Thanks again. But my question is simple. Can a view model be used in a detail view? I did not ask about oranges or if the EF source code was written in an award winning way. One step at a time Bruce One step at a time. All you are doing is adding confusion
to the already confused.
So I will ask again.. Can a view model be used in a details view. If so can you point me to an example of such things happening with a single table view model??
Here is the useless and very confusing microsoft tutorial that I have done almost 10 time.. it never compiles or works and it is all over the place
The ViewModel type Jobs_ViewModel_Class does not match the View fields and the model definition (at the top of the View) is a collection when you need a single type.
AppDev01
So I will ask again.. Can a view model be used in a details view. If so can you point me to an example of such things happening with a single table view model??
Your question is like asking, "Can I drive a car to work?". "What about a truck, can I drive a truck to work?" The answer is yes of course.
By definition a View Model is nothing more than a Model for a View - a simply class that contains properties. What's crazy is you are technically using View Models.
I believe the problems you are having has to do with understanding terms, C# language constructs, and the MVC framework. That's a tall order. It takes effort and time to learn this stuff. Unfortunately, the community and tutorials are unable to reach
you because you do not have the fundamental knowledge and you struggle to understand the solutions provided.
My best recommendation is going through the tutorial in my last post. It has an example of a View Model around step 7.
Thank you sadly the code first approach does not work for me and adds even more confusion to the mix.
It's not that I don't understand c or mvc.. I program every day. I don't understand the abstract concept of View Models .. I never understood why people feel that you don;t understand the whole picture why you don't understand a concept with in that picture.
I purposely avoid the code first model because it is dumb (to me) for me a well design database is a must and then I can build onto of that.
I will try to ask the question again. Can a view model work in a detail view.
IF the answer is Yes, My next question will be are there some basic example where this is shown where some of the higher concept stuff in not added to that will confuse the concept?
I don't need enumeration unless it required for the example. I am simply trying to wrap my head around how to make view models work since there is no plan english way to describe what they do and when you would use them and how you use them without all the
technical mumbo jumbo.
I not rejecting you suggestions... or the community's as you put it... I am trying to focus on one simple thing. I am looking for one simple clear unambiguous example showing this concept in the most basic form.
I am not trying to go back and learn C all over again.
Just and edit:
Currently in my program I am getting this error
Severity Code Description Project File Line Suppression State
Error CS1061 'IEnumerable<Jobs_ViewModel_Class>' does not contain a definition for 'POSIT_POSTING_DATE' and no accessible extension method 'POSIT_POSTING_DATE' accepting a first argument of type 'IEnumerable<Jobs_ViewModel_Class>' could be found (are you missing a using directive or an assembly reference?) JobsOpeningBackendSite C:\APP_DEV\JobsOpeningBackendSite\JobsOpeningBackendSite\Views\JOBS_POST_TBL\Details.cshtml 20 Active
In this situation is the problem that the view model has been turned into Iemumerable?
Whats confusing is that for this to display in the index it had to be made Ienumerable but I am guessing the display view can use that?
Is that what it is saying? Do I need to create a new view model for the display view?
I will never understand view models. Is there an alternative way where I can rename the fields on my forms differently from the fields on my database.
IF I can find a way to do that the heck with view models. As I can build all my views and alieses in SQL sever and just use the the SQL views vs trying to
do the over hard stuff with learning view models. Just looking for some ideas since I can't grasp the view model concept as it is way too complex for my brain.
You are using @model IEnumerable<JobsOpeningBackendSite.VIEW_MODELS.Jobs_ViewModel_Class> for both the index view that does show a list of items and uses "foreach" to but also for details
that shows only a single item and doesn't use foreach as it expect a single job object and not a list of jobs.
So this view should use rather @model JobsOpeningBackendSite.VIEW_MODELS.Jobs_ViewModel_Class so that it expects and process a single job object.
An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft
Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.
A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained
in the model.
In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.
<end>
I think this explains the purpose of the viewmodel in simplistic terms.
In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.
<end>
But also, the viewmodel is used to populate other objects such as a DTO or an ORM persistence model object for CRUD with a database as an example.
You see the concepts above come into play in the example code.
There is the create, edit, detail and index views for Author with each view working with the AuthorVM
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace PublishingCompany.Models
{
public class AuthorVM
{
public class Author
{
public int AuthorID { get; set; }
[Required(ErrorMessage = "First Name is required")]
[StringLength(50)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required")]
[StringLength(50)]
public string LastName { get; set; }
}
public List<Author> Authors { get; set; } = new List<Author>();
}
}
You see the AuthorDM (DM stands for Domain Model) in the Models folder working with the AuthorVM that is also in the Models folder. And AuthorDM is calling methods on the AuthorSvc that is doing CRUD with the database.
using System.Linq;
using ServiceLayer;
using Entities;
namespace PublishingCompany.Models
{
public class AuthorDM :IAuthorDM
{
private IAuthorSvc svc;
public AuthorDM(IAuthorSvc authorSvc)
{
svc = authorSvc;
}
public AuthorVM GetAll()
{
var vm = new AuthorVM();
var dtos = svc.GetAll().ToList();
vm.Authors.AddRange(dtos.Select(dto => new AuthorVM.Author()
{
AuthorID = dto.AuthorId,
FirstName = dto.FirstName,
LastName = dto.LastName
}).ToList());
return vm;
}
public AuthorVM.Author Find(int id)
{
var dto = svc.Find(id);
var author = new AuthorVM.Author
{
AuthorID = dto.AuthorId,
FirstName = dto.FirstName,
LastName = dto.LastName
};
return author;
}
public AuthorVM.Author Add()
{
return new AuthorVM.Author();
}
public void Add(AuthorVM.Author author)
{
var dto = new DtoAuthor
{
FirstName = author.FirstName,
LastName = author.LastName
};
svc.Add(dto);
}
public AuthorVM.Author Update(int id)
{
var dto = Find(id);
var author = new AuthorVM.Author
{
AuthorID = dto.AuthorID,
FirstName = dto.FirstName,
LastName = dto.LastName
};
return author;
}
public void Update(AuthorVM.Author author)
{
var dto = new DtoAuthor
{
AuthorId = author.AuthorID,
FirstName = author.FirstName,
LastName = author.LastName
};
svc.Update(dto);
}
public void Delete(int id)
{
var dto = new DtoId
{
Id = id
};
svc.Delete(dto);
}
}
}
You see the AuthorController calling methods on the AuthorDM, that is loading AuthorVM passing it to the controller and the controller is passing the AutorVM to the view. On the flip-side the AuthorDM is going to the AuthorVM to populate an AuthorDTO with
the AuthorDTO being persisted to the database.
using Microsoft.AspNetCore.Mvc;
using PublishingCompany.Models;
namespace PublishingCompany.Controllers
{
public class AuthorController : Controller
{
private IAuthorDM adm;
public AuthorController(IAuthorDM authorDM)
{
adm = authorDM;
}
public IActionResult Index()
{
return View(adm.GetAll());
}
public IActionResult Detail(int id = 0)
{
return id == 0 ? null : View(adm.Find(id));
}
public IActionResult Create()
{
return View(adm.Add());
}
[HttpPost]
public ActionResult Create(AuthorVM.Author author, string submit)
{
if (submit == "Cancel") return RedirectToAction("Index");
if (!ModelState.IsValid) return View(author);
adm.Add(author);
return RedirectToAction("Index");
}
public ActionResult Edit(int id = 0)
{
return id == 0 ? null : View(adm.Update(id));
}
[HttpPost]
public ActionResult Edit(AuthorVM.Author author, string submit)
{
if (submit == "Cancel") return RedirectToAction("Index");
if (!ModelState.IsValid) return View(author);
adm.Update(author);
return RedirectToAction("Index");
}
public IActionResult Delete(int id = 0)
{
if (id > 0) adm.Delete(id);
return RedirectToAction("Index");
}
public ActionResult Cancel()
{
return RedirectToAction("Index", "Home");
}
}
}
It's a simple concept the viewmodel.
If you find the post has answered your issue, then please mark post as 'answered'.
THANK YOU!!!!!!!!!!!!!!!!!!!!!!!!!! My Goodness!! PatriceSc Thank you, some one that gets it!!
Thank you a simple straight forward answer that was not loaded with overly technical noise!
So let me ask this.. and I think I may know the answer but I want to check to be sure with some one that is able to translate what it is Iam trying to accomplish here with out the other nonsense.
I created an Additional view model :
One that was a list
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace JobsOpeningBackendSite.VIEW_MODELS
{
public class JobsIndex_ViewModel_Class
{
[Key]
[DisplayName("Position Number")]
public short POSIT_NUMBER { get; set; }
[DisplayName("Job Posting Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public System.DateTime POSIT_POSTING_DATE { get; set; }
[DisplayName("Job Closing Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public System.DateTime POSIT_CLOSING_DATE { get; set; }
[DisplayName("Position Discription")]
public string POSIT_DESCRIPTION { get; set; }
[DisplayName("Job Link URL")]
public string POSIT_JOB_URL { get; set; }
public int PRID { get; set; }
public Nullable<bool> POSIT_POST_STATUS { get; set; }
}
//See: https://stackoverflow.com/questions/33044606/pass-ienumerable-viewmodel-to-view
//See: https://stackoverflow.com/questions/21694691/the-model-item-passed-into-the-dictionary-is-of-type-system-collections-generic
//See: http://techfunda.com/howto/262/list-data-using-viewmodel
public class JobsIenumViewModel
{
public IEnumerable<JobsIenumViewModel> jobs_ViewModel_Class { get; set; }
}
}
and one that could be use I guess for a single record: Detail
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace JobsOpeningBackendSite.VIEW_MODELS
{
public class JobDetails_ViewModel_Class
{
[Key]
[DisplayName("Position Number")]
public short POSIT_NUMBER { get; set; }
[DisplayName("Job Posting Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public System.DateTime POSIT_POSTING_DATE { get; set; }
[DisplayName("Job Closing Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public System.DateTime POSIT_CLOSING_DATE { get; set; }
[DisplayName("Position Discription")]
public string POSIT_DESCRIPTION { get; set; }
[DisplayName("Job Link URL")]
public string POSIT_JOB_URL { get; set; }
public int PRID { get; set; }
public Nullable<bool> POSIT_POST_STATUS { get; set; }
}
}
Now Both the Index and Detail Pages Render data as expected
But to me this seems like a lot of work to have to remake the view model multiple times.
In the view model for the Index... JobsIndex_ViewModel_Class
I had to add this at the bottom of it
public class JobsIenumViewModel
{
public IEnumerable<JobsIenumViewModel> jobs_ViewModel_Class { get; set; }
}
Now there is nothing in my source code that calls this... yet the program knows that the output is IEnumerable (I get that its the Interface thing going on here)
But because of it it requires me to make a new Viewmodel for each of my pages or should I name my non enumerated view mode something broader so it can be uses in other parts of my application since all its doing is allowing me to change the display names?
Again thank you so much for this clear answer! What took me days of trying to get a clear answer you did in seconds!
Thanks DA924 but the code first stuff is far to complicated for me to understand.
I can only understand database first... That AuthorDM part blows my skull into tiny pieces that leaves a mess in the backseat of car headed to
Toluca Lake.
The added complexity to the concept exceeds what I need to know. I will need to look up what DTO is but I will make note of this.
My goal is to have a simple and repeatable process in place along with the wizards help I can continue to build decent programs for my firm.
But I do thank you for the help and I know you have tried to help me in the past as well.
But I think I may be on a break trough to understanding something that has eluded me for years and I don;t want that understanding to
But because of it it requires me to make a new Viewmodel for each of my pages or should I name my non enumerated view mode something broader so it can be uses in other parts of my application since all its doing is allowing me to change the display
names?
A single viewmodel, a class, can have more than one class in it, as in the example of the TaskViewModels.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace ProgMgmntCore2UserIdentity.Models
{
public class TaskViewModels
{
public class TaskCreate
{
public int TaskId { get; set; }
[Required(ErrorMessage = "Task Name is required")]
[StringLength(50)]
public string TaskName { get; set; }
[Required(ErrorMessage = "Note is required")]
[StringLength(2000)]
public string Note { get; set; }
[Required(ErrorMessage = "Start Date is required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy hh:mm:ss tt}")]
public DateTime? StartDate { get; set; }
[Required(ErrorMessage = "Resource is required")]
public string ResourceId { get; set; }
public int ProjectId { get; set; }
[Required(ErrorMessage = "Duration is required")]
public string TaskDuration { get; set; }
[Required(ErrorMessage = "Status is required")]
public string Status { get; set; }
public List<SelectListItem> Statuses { get; set; }
public List<SelectListItem> Durations { get; set; }
public List<SelectListItem> Resources { get; set; }
}
public class TaskEdit
{
public int TaskId { get; set; }
[Required(ErrorMessage = "Task Name is required")]
[StringLength(50)]
public string TaskName { get; set; }
[Required(ErrorMessage = "Note is required")]
[StringLength(2000)]
public string Note { get; set; }
[Required(ErrorMessage = "Start Date is required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy hh:mm:ss tt}")]
public DateTime? StartDate { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy hh:mm:ss tt}")]
public DateTime? EndDate { get; set; }
public string ResourceId { get; set; }
public int ProjectId { get; set; }
public string TaskDuration { get; set; }
public string TaskSpent { get; set; }
public string Status { get; set; }
public List<SelectListItem> Statuses { get; set; }
public List<SelectListItem> Durations { get; set; }
public List<SelectListItem> Resources { get; set; }
public List<SelectListItem> Spents { get; set; }
}
public List<TaskEdit> Tasks { get; set; }
}
}
If you find the post has answered your issue, then please mark post as 'answered'.
But because of it it requires me to make a new Viewmodel for each of my pages or should I name my non enumerated view mode something broader so it can be uses in other parts of my application since all its doing is allowing me to change the display names?
Wrapping a single collection in a class has no benefit. Plus the code has a bug as I doubt you mean to create a collection of JobsIenumViewModel where each item has a collection of JobsIenumViewModel.
public class JobsIenumViewModel
{
public IEnumerable<JobsIenumViewModel> jobs_ViewModel_Class { get; set; }
}
I assume you mean
public class JobsIenumViewModel
{
public IEnumerable<JobDetails_ViewModel_Class> jobs_ViewModel_Class { get; set; }
}
The pattern is beneficial,however, when modeling an SQL JOIN in C# syntax. This is just an example to convey the concept.
public class JobsIenumViewModel
{
public int JobId {get; set}
public string JobType {get; set;}
public List<JobDetails_ViewModel_Class> jobs_ViewModel_Class { get; set; }
}
AppDev01
But because of it it requires me to make a new Viewmodel for each of my pages or should I name my non enumerated view mode something broader so it can be uses in other parts of my application since all its doing is allowing me to change the display names?
Just define a collection. No need to wrap the collection in the class. It just makes for extra code.
That is good to know. Its Still unclear what a view model is and why it exist and why it would not be a partial class which makes more sense to me but oh well.
But after re-reading the link I do have setup incorrectly (not sure why the complier allowed it to work... but you say this is a bug... can you in non-technical terms share with me why that would be a bug and what I have written is doing what vs what it
should be doing in a non technical way? If that is possible.
You wrote that I am wrapping ad single collection (What does that mean in non-technical terms?)
Same with creating a collection of JobsIenumViewModels?
Is there a way to step in to the program to see what it is that I can creating with this bug... I think that will help my non technical brain get what it is you are saying...
So if I put a break point inside of the view model will I see the error manifest itself visually?
Just wondering as that may be easier than dumbing it down for someone with my limited technical ability
Also this:
The pattern is beneficial,however, when modeling an SQL JOIN in C# syntax. This is just an example to convey the concept.
Is there a tutorial I can read up on this part as I am not getting the concept? why would a do a join in a view model and not in a SQL sever view and just call that view with the Entity Frame work's wizard and just treat it as just another table like structure?
Just wondering why this over that?
And On this:
Just define a collection. No need to wrap the collection in the class. It just makes for extra code.
Yeah, there is a edit.cshtml and a create.cshtml that have different views of a Task in Task functionality
That is good to know. Its Still unclear what a view model is and why it exist and why it would not be a partial class which makes more sense to me but oh well.
I think I gave a clear definition of the purpose of a viewmodel with example in a prior post in this thread.
If you find the post has answered your issue, then please mark post as 'answered'.
Thanks DA924 but the code first stuff is far to complicated for me to understand.
Where do you see any database code being used anywhere in the code I have shown you? I do not believe that DB code of any sort should be used directly in the controller of the MVC UI design pattern. That is not seperation of concerns or seperation of duty
that MVC was created for starting out on the desktop as a UI design pattern so that SoC can be implemented, with MVC being more recently implemented by Web UI solutions and very recently in MS's ASP.NET solutions.
I can only understand database first... That AuthorDM part blows my skull into tiny pieces that leaves a mess in the backseat of car headed to Toluca Lake.
Not even AuthorDM is directly using any database code, which is a domain model object. A domain model object does not directly use DB code.
My goal is to have a simple and repeatable process in place along with the wizards help I can continue to build decent programs for my firm.
Mr. Wizard, huh? :) You said a horrible word there 'Mr. Wizard' IMO that I bring out the holy cross, cringe and puke on that robs any software developer on the basics of how to program effectively in using Object Oriented Programming.
I'll say one more thing. You are right there in the fog of the Twilight Zone where you are aware of the domain, becuase I consider a viewmodel as part of the domain. But on the other hand, you have confused the persistence model/ORM/EF as part of the domain
as it's being directly used by the MVC controller.
Member
148 Points
677 Posts
Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.viewres...
Jan 13, 2020 10:27 PM|AppDev01|LINK
There is always something with MVC... has any one every run into this error?
This is the error I am getting
This is the view model thing
This is the tutorial and my source looks similar but I am getting this wacky error any ideas?
When I change the return to
The error changes to
Cannot implicitly convert type system.web.mvc.viewresult to system.action...
All-Star
58174 Points
15647 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 13, 2020 11:00 PM|bruce (sqlwork.com)|LINK
you should learn C#.
you declared a function to return an an object of type "Action", but are trying to return an object of type "List<Jobs_ViewModel_Class>". C# is type safe meaning its a syntax error assign object of the wrong type.
when you tried return View(...), it also is not of type "Action", but rather "ViewResult", which inherits from "ActionResult". again a type mismatch.
note: "Action" is generic type that defines a type that is a delegate with no parameters and returns type void.
Contributor
4923 Points
4200 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 13, 2020 11:29 PM|DA924|LINK
This is the tutorial and my source looks similar but I am getting this wacky error any ideas?
cannot implicitly convert type 'system.web.mvc.viewresult' to 'system.action
What's wacky about it? It's a basic lack of understanding OO principles.
You cannot tell viewresult, a class/type that it's going to be an action another class/type. You can't tell a car object that it's going to be jet object.
How is a List<T> of Jobs_ViewModel_Class objects in a collection ever going to be an Action?
How can you take an ListOfJobs anaymous types result being returned in a Linq projection and make it be a known type of Jobs_ViewModel_Class in a collection a List<T>?
If not that the code blew up with the exception you got, it would have returned nothing out of the method, becuase the projection used anaymous type instead of a projection being projected using a custom type of Jobs_ViewModel_Class is never done.
https://csharp-station.com/Tutorial/Linq/Lesson02
Participant
1320 Points
491 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 01:55 AM|jiadongm|LINK
Hi AppDev01,
The type of return must be the same as the type of the method or have an inheritance relationship. Here, if you just want to get the list you can change Action to List<Jobs_ViewModel_Class>. If you want to return a view, you should change it to ActionResult.
Best Regards,
Jiadong Meng
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 05:06 PM|AppDev01|LINK
I fixed that ... I was a type and it should have been Action Result. That was fixed...
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 05:21 PM|AppDev01|LINK
Yes the type was on my part but the tutorial has some other issues and I found a better one.
But Let me ask you all this... I am trying to display my a view model in a detail view vs the table that it returns by default when the wizard builds it.
As I stated before I don;t understand view models very well and all of the reading and tutorial over the years of trying to get a better grasp of it...I just don;t get so I am trying to write myself a small source code example that makes sense to me that I can reference that way I will be able to use them if I make my source codes follow the same pattern each time.
THis is what I have
But I am getting an error : Cannot implicitly convert type 'JobsOpeningBackendSite.JOBS_POST_TBL' to 'JobsOpeningBackendSite.VIEW_MODELS.Jobs_ViewModel_Class
What is odd in a system that I wrote 3 years about this type of thing worked but Instead of a sql table I created a sql view.
Is that some thing that I have to do here instead of using the table?
In my current production application I have this. which is the same thing that I am trying to do now...
So I am not sure what I am doing wrong now??
Do you use the view model in the controller or do I just use them i the view
All-Star
53011 Points
23596 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 05:54 PM|mgebhard|LINK
I need to ask a few clarifying questions as the code is a bit confusing. Is the controller named JOBS_POST_TBL? Can you provide the source for both the Jobs_ViewModel_Class and jOBS_POST_TBL class?
Actually I have a better idea. Create a test project to play with View models and whatever else you like. I recommend going through the standard Getting started with MVC and EF 6 tutorial. That will give us (you and the community) a common baseline project.
https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 06:12 PM|AppDev01|LINK
Sure... My goal here is to replace all the places where the wizard used the the Sql Table JOBS_POST_TBL with the view model:
The control is name JOB_POST_TBLController
So I made the view model and the error stated it needed to be something called enumerated so I made it to that. (yes the concept of enumeration has haunted me for a long time so I just found an example and made it so as I don't know what they mean by enumeration when it comes to programming even thought I have read about ... there is no basic plain English definition on it's meaning as it is all so technical... but if it means that it needs to be countable (If it does mean it needs to be countable why don;t they just say that vs some long technical meaningless word?) then that is what I did I think because it works for the Index view using a view model.
But I think that enumeration requirement has caused the view model to not be compatible with other other views... sadly.
But here is what I have
View Model
Controller
Index View That works with the enumerated View Model
The Details View that does not work with the view model
I would also like to get the created to work with the view model
It has not been changed from the wizards setup
All-Star
58174 Points
15647 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 06:29 PM|bruce (sqlwork.com)|LINK
if you're going to use a strongly typed language like C#, you should learn what types are. a bag (list) of oranges is not the same as an individual orange.
also you should run the EF queries in the controller via .ToList(), rather than in the view. EF queries are run every time your code iterates the query (foreach). .First() is hardly to get the first element. .Single() is hardly when there should only be one.
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 06:47 PM|AppDev01|LINK
Not sure what you mean and how that addresses or even helps with the question.
Its not about what I should do... it what I know how to do. I don;t really care about best practices as there is no such thing.
The best practice is what allows you to get a working program out the door and working well for your operation.
Is it the tightest who knows... All that "you should stuff" you need to tell that to microsoft as all I did was click on new mvc project and this is what that
option built using the visual studio wizard.
As for the I should use types... for the last 3 years of me finding this site and asking for help with some very hard to understand concepts ... that has been a constant refrain of yours... Sorry bruce it's not going to happen. All of the tutorials that I have found show the patterns that I ended up using... they USE VAR.... I USE VAR done and dusted... if they don;t type I don't type.
Maybe you should report them to the type police but get off my back about that please... typing will not help me and if they programming tools does not require it,, then its not going to happen as it will just adds to the confusion for me as it adds a layer of complication to a very hard concept to follow already.
Thanks again. But my question is simple. Can a view model be used in a detail view? I did not ask about oranges or if the EF source code was written in an award winning way. One step at a time Bruce One step at a time. All you are doing is adding confusion to the already confused.
So I will ask again.. Can a view model be used in a details view. If so can you point me to an example of such things happening with a single table view model??
Here is the useless and very confusing microsoft tutorial that I have done almost 10 time.. it never compiles or works and it is all over the place
https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-3
All-Star
53011 Points
23596 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 07:17 PM|mgebhard|LINK
The ViewModel type Jobs_ViewModel_Class does not match the View fields and the model definition (at the top of the View) is a collection when you need a single type.
Your question is like asking, "Can I drive a car to work?". "What about a truck, can I drive a truck to work?" The answer is yes of course.
By definition a View Model is nothing more than a Model for a View - a simply class that contains properties. What's crazy is you are technically using View Models.
I believe the problems you are having has to do with understanding terms, C# language constructs, and the MVC framework. That's a tall order. It takes effort and time to learn this stuff. Unfortunately, the community and tutorials are unable to reach you because you do not have the fundamental knowledge and you struggle to understand the solutions provided.
My best recommendation is going through the tutorial in my last post. It has an example of a View Model around step 7.
https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/
Once you have completed the tutorial above, the community will be better equipped to help as we (the community) will have the same project.
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 09:02 PM|AppDev01|LINK
Thank you sadly the code first approach does not work for me and adds even more confusion to the mix.
It's not that I don't understand c or mvc.. I program every day. I don't understand the abstract concept of View Models .. I never understood why people feel that you don;t understand the whole picture why you don't understand a concept with in that picture.
I purposely avoid the code first model because it is dumb (to me) for me a well design database is a must and then I can build onto of that.
I will try to ask the question again. Can a view model work in a detail view.
IF the answer is Yes, My next question will be are there some basic example where this is shown where some of the higher concept stuff in not added to that will confuse the concept?
I don't need enumeration unless it required for the example. I am simply trying to wrap my head around how to make view models work since there is no plan english way to describe what they do and when you would use them and how you use them without all the technical mumbo jumbo.
I not rejecting you suggestions... or the community's as you put it... I am trying to focus on one simple thing. I am looking for one simple clear unambiguous example showing this concept in the most basic form.
I am not trying to go back and learn C all over again.
Just and edit:
Currently in my program I am getting this error
In this situation is the problem that the view model has been turned into Iemumerable?
Whats confusing is that for this to display in the index it had to be made Ienumerable but I am guessing the display view can use that?
Is that what it is saying? Do I need to create a new view model for the display view?
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 09:08 PM|AppDev01|LINK
Actually let me try another approach.
I will never understand view models. Is there an alternative way where I can rename the fields on my forms differently from the fields on my database.
IF I can find a way to do that the heck with view models. As I can build all my views and alieses in SQL sever and just use the the SQL views vs trying to
do the over hard stuff with learning view models. Just looking for some ideas since I can't grasp the view model concept as it is way too complex for my brain.
THanks
All-Star
58174 Points
15647 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 09:27 PM|bruce (sqlwork.com)|LINK
you need understand the parameter passing and assignment. you must understand why the following statements are type errors.
Car car = new List<Car>(); //type error
or
public void MyMethod1(List<Car> cars) {}
public void MyMethod2(Car car) {} ...
MyMethod1(new Car()); //type error
MyMethod2(new List<Cars>()); //type error
All-Star
48510 Points
18071 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 09:27 PM|PatriceSc|LINK
Hi,
You are using @model IEnumerable<JobsOpeningBackendSite.VIEW_MODELS.Jobs_ViewModel_Class> for both the index view that does show a list of items and uses "foreach" to but also for details that shows only a single item and doesn't use foreach as it expect a single job object and not a list of jobs.
So this view should use rather @model JobsOpeningBackendSite.VIEW_MODELS.Jobs_ViewModel_Class so that it expects and process a single job object.
Contributor
4923 Points
4200 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 09:42 PM|DA924|LINK
As I stated before I don;t understand view models very well.
Well lets start by understanding the roles of the model, view and the controller. And I think their purposes are defined well in the link.
https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models-views-and-controllers-cs
<copied>
An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.
A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.
In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.
<end>
I think this explains the purpose of the viewmodel in simplistic terms.
https://www.dotnettricks.com/learn/mvc/understanding-viewmodel-in-aspnet-mvc
<copied>
In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.
<end>
But also, the viewmodel is used to populate other objects such as a DTO or an ORM persistence model object for CRUD with a database as an example.
You see the concepts above come into play in the example code.
There is the create, edit, detail and index views for Author with each view working with the AuthorVM
You see the AuthorDM (DM stands for Domain Model) in the Models folder working with the AuthorVM that is also in the Models folder. And AuthorDM is calling methods on the AuthorSvc that is doing CRUD with the database.
You see the AuthorController calling methods on the AuthorDM, that is loading AuthorVM passing it to the controller and the controller is passing the AutorVM to the view. On the flip-side the AuthorDM is going to the AuthorVM to populate an AuthorDTO with the AuthorDTO being persisted to the database.
It's a simple concept the viewmodel.
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 09:50 PM|AppDev01|LINK
THANK YOU!!!!!!!!!!!!!!!!!!!!!!!!!! My Goodness!! PatriceSc Thank you, some one that gets it!!
Thank you a simple straight forward answer that was not loaded with overly technical noise!
So let me ask this.. and I think I may know the answer but I want to check to be sure with some one that is able to translate what it is Iam trying to accomplish here with out the other nonsense.
I created an Additional view model :
One that was a list
and one that could be use I guess for a single record: Detail
Now Both the Index and Detail Pages Render data as expected
But to me this seems like a lot of work to have to remake the view model multiple times.
In the view model for the Index... JobsIndex_ViewModel_Class
I had to add this at the bottom of it
Now there is nothing in my source code that calls this... yet the program knows that the output is IEnumerable (I get that its the Interface thing going on here)
But because of it it requires me to make a new Viewmodel for each of my pages or should I name my non enumerated view mode something broader so it can be uses in other parts of my application since all its doing is allowing me to change the display names?
Again thank you so much for this clear answer! What took me days of trying to get a clear answer you did in seconds!
Thank you!
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 10:01 PM|AppDev01|LINK
Thanks DA924 but the code first stuff is far to complicated for me to understand.
I can only understand database first... That AuthorDM part blows my skull into tiny pieces that leaves a mess in the backseat of car headed to Toluca Lake.
The added complexity to the concept exceeds what I need to know. I will need to look up what DTO is but I will make note of this.
My goal is to have a simple and repeatable process in place along with the wizards help I can continue to build decent programs for my firm.
But I do thank you for the help and I know you have tried to help me in the past as well.
But I think I may be on a break trough to understanding something that has eluded me for years and I don;t want that understanding to
get lost in the technical sauces. Thanks!
Contributor
4923 Points
4200 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 10:08 PM|DA924|LINK
But because of it it requires me to make a new Viewmodel for each of my pages or should I name my non enumerated view mode something broader so it can be uses in other parts of my application since all its doing is allowing me to change the display names?
A single viewmodel, a class, can have more than one class in it, as in the example of the TaskViewModels.
All-Star
53011 Points
23596 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 10:11 PM|mgebhard|LINK
Wrapping a single collection in a class has no benefit. Plus the code has a bug as I doubt you mean to create a collection of JobsIenumViewModel where each item has a collection of JobsIenumViewModel.
I assume you mean
public class JobsIenumViewModel { public IEnumerable<JobDetails_ViewModel_Class> jobs_ViewModel_Class { get; set; } }
The pattern is beneficial,however, when modeling an SQL JOIN in C# syntax. This is just an example to convey the concept.
public class JobsIenumViewModel { public int JobId {get; set} public string JobType {get; set;} public List<JobDetails_ViewModel_Class> jobs_ViewModel_Class { get; set; } }
Just define a collection. No need to wrap the collection in the class. It just makes for extra code.
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 10:15 PM|AppDev01|LINK
Ahhh so I can call using a (.)Dot
So TaskViewModels.TaskCreate and so on?
That is good to know. Its Still unclear what a view model is and why it exist and why it would not be a partial class which makes more sense to me but oh well.
If it works it works . Thank you!
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 10:28 PM|AppDev01|LINK
Hi
mgebhard
I'm confused by what you mean.. there is a bug here?
The program seems to run. I got the example from here: https://stackoverflow.com/questions/33044606/pass-ienumerable-viewmodel-to-view
But after re-reading the link I do have setup incorrectly (not sure why the complier allowed it to work... but you say this is a bug... can you in non-technical terms share with me why that would be a bug and what I have written is doing what vs what it should be doing in a non technical way? If that is possible.
You wrote that I am wrapping ad single collection (What does that mean in non-technical terms?)
Same with creating a collection of JobsIenumViewModels?
Is there a way to step in to the program to see what it is that I can creating with this bug... I think that will help my non technical brain get what it is you are saying...
So if I put a break point inside of the view model will I see the error manifest itself visually?
Just wondering as that may be easier than dumbing it down for someone with my limited technical ability
Also this:
The pattern is beneficial,however, when modeling an SQL JOIN in C# syntax. This is just an example to convey the concept.
Is there a tutorial I can read up on this part as I am not getting the concept? why would a do a join in a view model and not in a SQL sever view and just call that view with the Entity Frame work's wizard and just treat it as just another table like structure? Just wondering why this over that?
And On this:
Just define a collection. No need to wrap the collection in the class. It just makes for extra code.
Isn't this statement contrary to what DA Posted which shows that I can add Multiple version of the view model in one view model?
Contributor
4923 Points
4200 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 14, 2020 10:55 PM|DA924|LINK
So TaskViewModels.TaskCreate and so on?
Yeah, there is a edit.cshtml and a create.cshtml that have different views of a Task in Task functionality
That is good to know. Its Still unclear what a view model is and why it exist and why it would not be a partial class which makes more sense to me but oh well.
I think I gave a clear definition of the purpose of a viewmodel with example in a prior post in this thread.
Contributor
4923 Points
4200 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 15, 2020 03:19 AM|DA924|LINK
Thanks DA924 but the code first stuff is far to complicated for me to understand.
Where do you see any database code being used anywhere in the code I have shown you? I do not believe that DB code of any sort should be used directly in the controller of the MVC UI design pattern. That is not seperation of concerns or seperation of duty that MVC was created for starting out on the desktop as a UI design pattern so that SoC can be implemented, with MVC being more recently implemented by Web UI solutions and very recently in MS's ASP.NET solutions.
https://en.wikipedia.org/wiki/Separation_of_concerns
https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/
https://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP
I can only understand database first... That AuthorDM part blows my skull into tiny pieces that leaves a mess in the backseat of car headed to Toluca Lake.
Not even AuthorDM is directly using any database code, which is a domain model object. A domain model object does not directly use DB code.
My goal is to have a simple and repeatable process in place along with the wizards help I can continue to build decent programs for my firm.
Mr. Wizard, huh? :) You said a horrible word there 'Mr. Wizard' IMO that I bring out the holy cross, cringe and puke on that robs any software developer on the basics of how to program effectively in using Object Oriented Programming.
I'll say one more thing. You are right there in the fog of the Twilight Zone where you are aware of the domain, becuase I consider a viewmodel as part of the domain. But on the other hand, you have confused the persistence model/ORM/EF as part of the domain as it's being directly used by the MVC controller.
https://blog.sapiensworks.com/post/2012/04/07/Just-Stop-It!-The-Domain-Model-Is-Not-The-Persistence-Model.aspx
It's not your falut, becuase that's what the tutorials for ASP.NET MVC teaches, and Mr. Wizard sends you down the path too.
Member
148 Points
677 Posts
Re: Sigh... can any one help with this error? cannot implicitly convert type 'system.web.mvc.vie...
Jan 21, 2020 04:12 PM|AppDev01|LINK
Oh well... it is what it is... I don't live and breath this stuff like some may do.
Understanding things is such a subjective science... there are concepts in MVC, VB, C#, data structures and programming that I will never understand..
No matter how may times I read it, Try It, and or use it. This wizard may be bad for you but a God for me.
There is no harm in not understanding all there is to know friend. Even what some my deem the basics..
Communities like this one are very helpful. I am sure if I was over at stack overflow I would be voted down out of existence.
So I do appreciate the help. Hopefully that helps you understand my point of view.