DBContext not saving modified entry - c#

I am developing a simple website where there are students and there are courses. What is interesting is I can't seem to add a course to my student and make it save. I call the savechanges() method but on my cshtml page, my viewbag does not contain the updated student. Here is what I mean.
Here you can see my ViewBag.Student contains a valid student that has been modified to include two courses under PendingCourses. However, when I load my cshtml page, my ViewBag.Student contains:
So there is definitely some disconnect although I can't figure out what it is. So basically my Details page sets the ViewBag by doing a where statement on the context. This context is modified and saved with the AddCourseToStudent function and then the ViewBag.Student is read in the cshtml. Any help is much appreciated. Below are my files for reference.
Details Function:
// GET: Student/Details/5
[Authorize]
public ActionResult Details(int id)
{
using (var context = new StudentDbContext())
{
ViewBag.Student = context.Students.Where(u => u.id == id).FirstOrDefault();
}
var context2 = new ApplicationDbContext();
var userList = context2.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList();
ViewBag.Users = userList;
return View();
}
CSHTML:
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
SchoolRegistration.Models.Student student = ViewBag.Student;
List<SchoolRegistration.Models.Course> completedCourses = student.CompletedCourses;
List<SchoolRegistration.Models.Course> pendingCourses = student.PendingCourses;
List<SchoolRegistration.Models.Course> failedCourses = student.FailedCourses;
List<int> yearRange = new List<int>();
if (completedCourses != null) {
foreach (SchoolRegistration.Models.Course course in completedCourses)
{
if (!yearRange.Contains(course.Year))
{
yearRange.Add(course.Year);
}
}
}
if (pendingCourses != null)
{
foreach (SchoolRegistration.Models.Course course in pendingCourses)
{
if (!yearRange.Contains(course.Year))
{
yearRange.Add(course.Year);
}
}
}
if (failedCourses != null)
{
foreach (SchoolRegistration.Models.Course course in failedCourses)
{
if (!yearRange.Contains(course.Year))
{
yearRange.Add(course.Year);
}
}
}
yearRange.Sort();
}
<h2>Details</h2>
#if (TempData["Success"] != null)
{
if (TempData["Success"] == "nocourse")
{
<div style="background-color:aliceblue">
<p><strong>Success:</strong>Create Course?</p>
</div>
}
else
{
<div style="background-color:aliceblue">
<p><strong>Success:</strong> #TempData["Success"].ToString()</p>
</div>
}
}
<h3>#student.FirstName #student.LastName - #student.StudentID</h3>
<h4>#student.GradeLevel - #student.ExpectedGraduation</h4>
<h3>Degree Audit</h3>
#using (Html.BeginForm("GetCourse", "Student", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<p>Start Year: #Html.DropDownList("startYear", (IEnumerable<SelectListItem>)yearRange.ToList().Select(rr => new SelectListItem { Value = rr.ToString(), Text = rr.ToString() }).ToList(), "Select...") Start Semester: #Html.DropDownList("startSemester", EnumHelper.GetSelectList(typeof(SchoolRegistration.Models.Semesters)), "Select...")</p>
<p>End Year: #Html.DropDownList("endYear", (IEnumerable<SelectListItem>)yearRange.ToList().Select(rr => new SelectListItem { Value = rr.ToString(), Text = rr.ToString() }).ToList(), "Select...") End Semester: #Html.DropDownList("endSemester", EnumHelper.GetSelectList(typeof(SchoolRegistration.Models.Semesters)), "Select...")</p>
<input type="submit" value="Search" id="btnStudentFilter" />
}
<h3>Course Management</h3>
#using (Html.BeginForm("GetCourseForStudent", "Student", FormMethod.Post))
{
#Html.AntiForgeryToken();
<hr />
<p><strong>Subject: </strong>#Html.DropDownList("cat", EnumHelper.GetSelectList(typeof(SchoolRegistration.Models.Categories)), "Select...")</p>
<p><strong>CAT NO: </strong>#Html.TextBox("CourseId")</p>
<p><strong>Section: </strong>#Html.TextBox("SectionId")</p>
<p><strong>Year: </strong>#Html.TextBox("Year")</p>
<p><strong>Semester: </strong>#Html.DropDownList("semester", EnumHelper.GetSelectList(typeof(SchoolRegistration.Models.Semesters)), "Select...")</p>
<input type="submit" value="Search" />
}
#if (TempData["RetrievedCourses"] != null)
{
List<SchoolRegistration.Models.Course> courses = (List<SchoolRegistration.Models.Course>)TempData["RetrievedCourses"];
for (int i = 0; i < courses.Count; i++)
{
<p>#courses[i].Name - #courses[i].Category #courses[i].CourseId . #courses[i].SectionId - #courses[i].Credits Credits | #Html.ActionLink("Add to Student", "AddCourseForStudent", "Student", new { courseId = courses[i].id, studentId = student.id},null)</p>
}
<p>Course Search DIV Link</p>
}
AddCourseToStudent:
public ActionResult AddCourseForStudent(int courseId, int studentId)
{
using (var context = new StudentDbContext())
{
Student student = context.Students.Where(u => u.id == studentId).FirstOrDefault();
Course course = context.Courses.Where(u => u.id == courseId).FirstOrDefault();
List<Course> completed = student.CompletedCourses;
List<Course> pending = student.PendingCourses;
List<Course> failed = student.FailedCourses;
if (completed == null)
completed = new List<Course>();
student.CompletedCourses = completed;
if (pending == null)
pending = new List<Course>();
student.PendingCourses = pending;
if (failed == null)
failed = new List<Course>();
student.FailedCourses = failed;
pending.Add(course);
try
{
context.Entry(student).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
ViewBag.Student = student;
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
TempData["Success"] = "Courses added to student.";
return Redirect(Request.UrlReferrer.ToString());
}
Models:
public class InstructorViewModels
{
}
public enum GradeLevels
{
Freshman,
Sophmore,
Junior,
Senior,
Graduate
}
public enum Categories
{
CSCI
}
public enum Semesters
{
FA,
SP,
S1,
S2,
S3,
IN
}
public enum CourseTypes
{
Humanities
}
public class Student
{
public int id { get; set; }
[Required]
public int StudentID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string MiddleName { get; set; }
[Required]
public GradeLevels GradeLevel { get; set; }
[Required]
public List<Course> CompletedCourses { get; set; }
[Required]
public List<Course> PendingCourses { get; set; }
[Required]
public List<Course> FailedCourses { get; set; }
[Required]
public int ExpectedGraduation { get; set; }
}
public class Course
{
public int id { get; set; }
public int CourseId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int SectionId { get; set; }
[Required]
public Categories Category { get; set; }
[Required]
public int Credits { get; set; }
[Required]
public Semesters Semester { get; set; }
[Required]
public int Year { get; set; }
[Required]
public string InstructorId { get; set; }
public CourseTypes CourseType { get; set; }
}
Database:

Related

Trying to add an object to a list in a Model via Html Form

I've been trying to add an object to a list in my model, via the HTML form
My Recipe Class:
public long Id { get; set; }
private string _key;
public string Key
{
get
{
if (_key == null)
{
_key = Regex.Replace(Title.ToLower(), "[^a-z0-9]", "-");
}
return _key;
}
set { _key = value; }
}
[Required]
[Display(Name = "Ingredienser")]
public string Ingredients { get; set; }
[Required]
[Display(Name = "Fremgangsmåde")]
public string Method { get; set; }
[Required]
[Display(Name = "Titel")]
public string Title { get; set; }
public DateTime Posted { get; set; }
public List<Comment> Comments { get; set; } = new List<Comment>();
public List<Rating> Ratings { get; set; } = new List<Rating>();
public string Author { get; set; }
public Rating NewRating { get; set; } = new Rating();
public double CalculateRating()
{
if (Ratings.Count == 0)
return 0;
else
return Ratings.Average(x => x.Value);
}
What i've been trying:
#using (Html.BeginForm("Rating", "Home", FormMethod.Post, Model.Id))
{
<p>
#Html.LabelFor(x => x.NewRating)
#Html.RadioButtonFor(x => x.NewRating.Value, 0)
#Html.RadioButtonFor(x => x.NewRating.Value, 1)
#Html.RadioButtonFor(x => x.NewRating.Value, 2)
#Html.RadioButtonFor(x => x.NewRating.Value, 3)
</p>
<p>
<button type="submit">Giv Karakter</button>
</p>
}
and here's the method i'm posting to:
public IActionResult Rating([FromForm] int RecipeId, Rating rating)
{
rating.Posted = DateTime.Now;
var recipe = _db.Recipes.Where(x => x.Id == RecipeId).Include(e =>
e.Comments).FirstOrDefault();
recipe.Ratings.Add(rating);
_db.Update<Recipe>(recipe);
_db.SaveChanges();
return RedirectToAction("Index");
}
My problem is that i am not recieving a ratings object in my Rating method as i should, i can't figure out how to directly add an object to a list via a form
(this list is of course empty, since i cant add items to it yet)
Due to MVC binder behavior and deserialization, please keep the same instance name, during POST. So change the following line like below ("Rating NewRating")
public IActionResult Rating([FromForm] int RecipeId, Rating NewRating)
That should work.

Adding comment to post in ASP.NET MVC

EDIT: I am trying to add a comment to a post in my mvc application but my action does not seem to work. When I reach the Action I want to pass on an Id from a Post (the Id from the table/model FormalBlog) but the newPost.Post = model.Post is null and when the action reaches the db.SaveChanges it throws an System.Data.Entity.Validation.DbEntityValidationException.
Below is my action and my PostIndexViewModel:
public ActionResult Comment(PostIndexViewModel model, FormalBlog Post)
{
var userName = User.Identity.Name;
var author = db.Users.SingleOrDefault(x => x.UserName == userName);
Comment newPost = new Comment();
newPost.Author = author;
newPost.Text = model.Text;
newPost.Post = model.Post;
db.Comments.Add(newPost);
db.SaveChanges();
return RedirectToAction("ShowBlogs", "Blog");
}
}
public class PostIndexViewModel
{
public string Id { get; set; }
public ICollection<FormalBlog> FormalBlogs { get; set; }
public FormalBlog NewFormalBlog { get; set; } = new FormalBlog();
public Category NewCategory { get; set; } = new Category();
public ICollection<Category> Categories { get; set; }
public List<SelectListItem> SelectedCategories { get; set; }
public int[] CategoryIds { get; set; }
public Category CategoryN { get; set; }
public ICollection<Meeting> Meetings { get; set; } //testrad
// public int Id { get; set; }
public string Text { get; set; }
public ApplicationUser Author { get; set; }
public Comment NewComment { get; set; }
public FormalBlog Post { get; set; }
}
and here is the code for my view:
#model XP_Scrum_Grupp2.Controllers.PostIndexViewModel
#using (Html.BeginForm("Comment", "Blog", new { formal = Model }, FormMethod.Post, new { id = Model.Id }))
{
<div class="comment-form-container">
<form class="comment-form" data-action="#Url.Action("Comment", "Blog")">
#Html.HiddenFor(m => m.Id)
<div>#Html.DisplayFor(m => m.Author)</div>
<div>
<div>#Html.LabelFor(m => m.Text)</div>
#Html.TextAreaFor(m => m.Text, new { Class = "comment-text", rows = "3", cols = "50" })
</div>
<div class="comment-result" style="display: none;">
<span class="comment-result-text">An error occurred</span>
</div>
<div>
<button type="submit" class="comment-form-submit">Submit comment</button>
</div>
</form>
</div>
}
Your view does not assign any value to model.NewComment. So when you access model.NewComment.Text it will throw Null reference exception since model.NewComment is null.
You assign new text to model's Test property. So you should use model.Text instead of model.NewComment.Text
public ActionResult Comment(PostIndexViewModel model)
{
var userName = User.Identity.Name;
var author = db.Users.SingleOrDefault(x => x.UserName == userName);
Comment newPost = new Comment();
newPost.Author = author;
newPost.Text = model.Text;
newPost.Post = model.Post;
db.Comments.Add(newPost);
db.SaveChanges();
return RedirectToAction("ShowBlogs", "Blog");
}
You are not posting the any data as model.NewComment.Text so the error occures because of NewComment object is null.
#Html.TextAreaFor(m => m.Text, new { Class = "comment-text", rows = "3", cols = "50" })
So, try to change it;
newPost.Text = model.NewComment.Text;
to
newPost.Text = model.Text;

How to write Users checkbox checks into multiple records in database - using MVC, C#, Razor, nHibernate

So im trying to insert into my database the values from check boxes that the user checked.
In my ViewModel:
[Display(Name = "Title")]
public string Title { get; set; }
public IEnumerable<SelectListItem> UserTitlelist { get; set; }
public IEnumerable<SelectListItem> Titles { get; set; }
In my View:
#foreach (var item in Model.Titles)
{
<label class="managelabel" style="padding: 0 5px 0 5px;"><input name="Title" type="checkbox" value="#item.Value" #checkedcheckbox> #item.Text</label>
}
In my Controller:
var titleToInsert = new UserTitle
{
UserId = currentUserId,
TitleId = model.Title[];
};
UserManagerService.UpdateUserTitles(titleToInsert);
In UserManagerService:
public static int UpdateUserTitles(UserTitle userTitle)
{
using (ITransaction transaction = Context.BeginTransaction())
{
foreach (var x in userTitle)
{
Context.Save(userTitle);
}
transaction.Commit();
}
return 0;
}
You view model is incorrect and has no relationship at all to what you are editing. And SelectListItem is a class for use in #Html.DropDownListFor(), not for a collection of checkboxes.
You view models should be
public class TitleVM
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class UserTitleVM
{
.... // other properties
public List<TitleVM> Titles { get; set; }
}
And in the view
#model UserTitleVM
#using (Html.BeginForm())
{
....
for(int i = 0; i < Model.Titles.Count; i++)
{
#Html.HiddenFor(m => m.Titles[i].ID)
#Html.CheckBoxFor(m =>m.Titles[i].IsSelected)
#Html.LabelFor(m => m.Titles[i].IsSelected, Model.Titles[i].Name)
}
and in the controller
public ActionResult Edit(UserTitleVM model)
{
// Get the ID's of the selected titles
List<int> selectedTitles = model.Titles.Where(t => t.IsSelected).Select(t => t.ID);
....
I found the answer is quite simple:
in the controller:
var myList = Request.Form["Title"];
foreach (var item in myList.Split(','))
{
var titleToInsert = new UserTitle
{
UserId = currentUserId,
TitleId = Convert.ToInt32(item)
};
UserManagerService.UpdateUserTitles(titleToInsert);
}
then in UserManagerService:
public static int UpdateUserTitles(UserTitle userTitle)
{
using (ITransaction transaction = Context.BeginTransaction())
{
Context.Save(userTitle);
transaction.Commit();
}
return 0;
}
This way each record gets saved individually

Creating a dropdown in MVC3 C# with ViewModel and easy model binding on POST back.

I have this problem where i want to make 7 dropdowns for each day of the week.
In each one of those dropdowns i wish to add the same data.
My ViewModel:
public class WeekDienstCreateViewModel
{
public WeekDienst weekDienst {get; set;}
public List<DienstPerWeekDienst> diensten { get; set; }
public WeekDienstCreateViewModel() { }
}
My Create Method in Controller:
As u can see I add everything allready except DienstId which is want to add with my dropdowns.
public ActionResult Create(int id)
{
WeekDienst wd = _service.FindWeekDienst(id);
WeekDienstCreateViewModel vm = new WeekDienstCreateViewModel();
vm.diensten = new List<DienstPerWeekDienst>();
vm.weekDienst = wd;
for (int i = 1; i <= 7; i++)
{
DienstPerWeekDienst dpwd = new DienstPerWeekDienst();
dpwd.volgnummer = i;
dpwd.WeekDienstId = wd.Id;
vm.diensten.Add(dpwd);
}
ViewBag.Diensten = _service.DienstenList(wd.AfdelingId);
return View(vm);
}
Classes:
public class DienstPerWeekDienst
{
[Key]
public int Id { get; set; }
[Required]
public int WeekDienstId { get; set; }
[Required]
public int DienstId { get; set; }
[Required]
[Range(1, 7)]
public int volgnummer { get; set; }
[ForeignKey("WeekDienstId")]
public virtual WeekDienst WeekDienst { get; set; }
[ForeignKey("DienstId")]
public virtual Dienst Dienst { get; set; }
public virtual ICollection<WeekDienst> WeekDiensten { get; set; }
}
public class WeekDienst
{
[Key]
public int Id { get; set; }
[Required]
public int AfdelingId { get; set; }
[Required]
[StringLength(5, ErrorMessage = "Value for {0} cannot exceed {1} characters.")]
[RegularExpression(#"^[a-zA-Z0-9]{5}$", ErrorMessage = "Verplicht 5 cijfers lang.")]
public string code { get; set; }
[DisplayName("Template")]
public bool template { get; set; }
[ForeignKey("AfdelingId")]
public virtual Afdeling Afdeling { get; set; }
}
And in my view i wish to create 7 dropdowns where i put in all my "Diensten" (class Dienst, fk in DienstPerWeekDienst). When I choose 1 i wish to add the "DienstId" into the "DienstPerWeekDienst" class.
So in my View i got this:
#foreach (var day in Model.diensten)
{
var currentDay=day;
#Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"))
}
I Wish to postback the chosen "Diensten" and create the "WeekDienst" but now i am just posting a null "DienstPerDienstWeekCreateViewModel". How am I able to fix this?
Thanks in Advance
FIX (Thanks to Siva Gopal)
I fixed this by doing:
#for (int i = 0; i < #Model.diensten.Count; i++)
{
#Html.HiddenFor(m => (m.diensten[i].volgnummer))
#Html.HiddenFor(m => (m.diensten[i].WeekDienstId))
#Html.DropDownListFor(m=> (m.diensten[i].DienstId), new SelectList(ViewBag.Diensten, "Value", "Text"))
}
You may try using
#foreach (var day in Model.diensten)
{
var currentDay=day;
#Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new { })
} //This uses the Lambda Expression. Your dropdown Name/Id would be 1,2,3 etc. based on currentDay value.
OR
#foreach (var day in Model.diensten)
{
var currentDay=day;
var dropdownName=string.Format("diensten[{0}]",day-1); //If you want to model bind the selected dropdown value to input entity in POST request. The final dropdownName format should match the hierarchy of the property inside input entity/object. Even without this name formation, you can still POST the selected value back using Jquery/Javascript.
#Html.DropDownList(dropdownName, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new {})
} //
Note for Value Post back/model bind on full Page submit:
To be able to model bind/POST back values to the server, the html element names corresponding to the properties should be rendered as follows: Suppose if you display Employee.Department.Name, then name of textbox, displaying the Department Name in View should match Department_ReferenceName_Inside_Employee.Name for model binding.
Model:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public Department EmpDepartment { get; set; }
public List SubOrdinates { get; set; }
}
public class Department
{
public string Name { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
//Prepare the model and send it to the view
Employee emp = new Employee { EmpDepartment = new Department { Name = "IT" } };
emp.SubOrdinates = new List<Employee> { new Employee { Name = "Emp1" }, new Employee { Name = "Emp2" } };
return View(emp);
}
[HttpPost]
public ActionResult Index(Employee emp)
{ //Put a break-point here and see how the modified values in view are flowing into emp..
return View(emp);
}
public ActionResult About()
{
return View();
}
}
View:
#model MvcApplication.Models.Employee
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.EmpDepartment.Name)
#Html.LabelForModel("SubOrdinates :")
for (int i = 0; i < #Model.SubOrdinates.Count; i++)
{
#Html.TextBoxFor(m => (m.SubOrdinates[i].Name))
}
<input type="submit" name="name" value="Submit" /> }
ViewSource/PageSource:
The above text box syntax will be rendered as :
<input id="EmpDepartment_Name" name="EmpDepartment.Name" type="text" value="IT" /> <!--See above html : name=EmpDepartment.Name -->
<label for="">SubOrdinates :</label>
<input id="SubOrdinates_0__Name" name="SubOrdinates[0].Name" type="text" value="Emp1" />
<input id="SubOrdinates_1__Name" name="SubOrdinates[1].Name" type="text" value="Emp2" /> <!--See above html for how collection item Name(s) are being renderd by view engine-->
<input type="submit" name="name" value="Submit" />
#foreach (var day in Model.diensten)
{
var currentDay = day;
#Html.DropDownListFor(x => currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"), new { #id = "DienstList" })
}
List<MvcApplication1.Models.Country> cntry = db.Countries.ToList();
SelectListItem sss = new SelectListItem();
List<SelectListItem> sltst = new List<SelectListItem>();
sss.Text = "Select";
sss.Value = "0";
sltst.Add(sss);
foreach (MvcApplication1.Models.Country s in cntry){
SelectListItem s1 = new SelectListItem();
s1.Text = s.Country1;
s1.Value = Convert.ToString(s.Id);
sltst.Add(s1);}
#Html.DropDownList("country", sltst, new { #id = "country" })

MVC template editor how to display items from two model

I hope I explain this correctly..
What I am trying to do is build up a session array with a list of products in.
Then display these on a form in text boxes with quantiles next to them and be able to submit them. I think I need to use template editor. But I don't know how to put data into the list of items.
This is how my session variable is currently being populated..
IList<EnqProduct> items2 = Session["enquiry"] as IList<EnqProduct>;
desc = desc.Replace(",", "");
EnqProduct item = new EnqProduct();
item.Id = (items2.Count + 1).ToString();
item.Product = desc;
item.Quantity = "0";
items2.Add(item);
So desc, can be productone, product two etc.
Enquiry Product model:
namespace MvcEditorTemplates.Models
{
public class EnqProduct
{
public string Id { get; set; }
public string Product { get; set; }
public string Quantity { get; set; }
}
}
Normal Enquiry Model:
public class Enquiry
{
public List<EnqProduct> EnqProduct { get; set; }
}
How i am trying to populate the model, but this is static. I need it to be populated from the array items:
var EnquiryModel = new Enquiry {
EnqProduct = items2.Select(c => new EnqProduct()
{
Quantity = c.Quantity,
Product = c.Product
})
};
Enquiry product template view:
#model MvcEditorTemplates.Models.EnqProduct
<div class="fl">
<p>
#Html.LabelFor(x => x.Product)
#Html.TextBoxFor(x => x.Product)
</p>
<p>
#Html.LabelFor(x => x.Quantity)
#Html.TextBoxFor(x => x.Quantity)
</p>
</div>
This is how im trying to get it to be displayed din the view:
#Html.EditorFor(model => model.EnqProduct)
EDIT:
at items2.Select(c => new EnqProduct()
i get a IEnumerbale error something about cast?
Try something like this:
public class ErrorMessage
{
public DateTime ErrorDate { get; set; }
public string ErrorText { get; set; }
public int DexRowId { get; set; }
}
public class Transaction
{
public string TransactionType { get; set; }
public string Processed { get; set; }
public DateTime UpdateDate { get; set; }
public int DexRowID { get; set; }
public string Text { get; set; }
}
public class Result
{
public List<ErrorMessage> errorMessageList { get; set; }
public List<Transaction> transactionList { get; set; }
}
In your controller:
List<Transaction> transactionList = ...;//query to populate your list;
List<ErrorMessage> errorMessageList = ...;//query to populate your list;
Result result = new Result();
result.ErrorMessageList = errorMessageList;
result.TransactionList = transactionList;
return View(result);
and in your view:
#model Models.Result
#{
ViewBag.Title = "Result";
Layout = "~/Views/Shared/_ResultLayout.cshtml";
}
EDIT:
#model IENumerable<MvcEditorTemplates.Models.EnqProduct>
#{
foreach( EnqProduct ep in #model)
{
.... your code comes here.........
}
}

Categories

Resources