Display Model info in a View MVC5 without DB Context - c#

so I'm new to MVC5 and I'm creating a website without the use of a DB context. How do I go about displaying Model info taken from fields into a view? I cannot use a DB context which would've made this a whole lot easier.
Here's my Controller:
using SaasSocialNetwork.Models;
using SSN.Shared.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using log4net;
namespace SaasSocialNetwork.Controllers
{
public class OpportunitiesController : Controller
{
ILog logger = LogManager.GetLogger(typeof(OpportunitiesController));
//
// GET: /Opportunities/
public ActionResult Index(OpportunityModel opportunity)
{
List<OpportunityModel> opportunities = new List<OpportunityModel>();
opportunities.Add(opportunity);
try
{
//multishops = TownBL.getMultishops().ToList();
return View(opportunities);
}
catch(Exception ex)
{
logger.Error(ex);
TempData["Warnning"] = ex.Message;
return View(opportunities);
}
finally
{
logger.Debug("<<Index");
}
//return View();
}
// GET: /Opportunities/Details/5
public ActionResult Details(OpportunityModel opportunity)
{
logger.Debug(">>Details");
try
{
//MultiShops multishop = TownBL.getMultishops().Single(m => m.ID == id);
//logger.InfoFormat("{0} Multi Shop Details", opportunity.Name);
//var list = new List<string> { "test1", "test2", "test3" };
return View("Details", opportunityModel);
}
catch (Exception ex)
{
logger.Error(ex);
return View("Details");
}
finally
{
logger.Debug("<<Details");
}
return View();
}
// GET: /Opportunities/Create
public ActionResult Create()
{
logger.Debug(">>Create(GET)");
try
{
return View("Create");
}
catch (Exception ex)
{
logger.Error(ex);
return View("Index");
}
finally
{
logger.Debug("<<Create");
}
//return View();
}
//
// POST: /Opportunities/Create
[HttpPost]
public ActionResult Create(OpportunityModel opportunity)
{
try
{
// TODO: Add insert logic here
OpportunityModel object1 = new OpportunityModel();
SSN.Shared.Interfaces.Opportunity opp = new Opportunity();
opp.Name = object1.Name;
opp.Description = object1.Description;
opp.ImageUrl = object1.ImageUrl;
opp.GuidID = object1.GuidID;
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Opportunities/Edit/5
//public ActionResult Edit(Guid GuidId)
//{
// logger.Debug(">>Edit(GET)");
// try
// {
// //MultiShops opportunity = TownBL.getMultishops().Single(m => m.ID == id);
// ViewBag.state = new List<SelectListItem>{
// new SelectListItem { Text = "Active", Value = "Active" },
// new SelectListItem { Text = "Suspended", Value ="Suspended"},
// };
// //return View(opportunity);
// }
// catch (Exception ex)
// {
// logger.Error(ex);
// return View();
// }
// finally
// {
// logger.Debug("<<Edit");
// }
//}
//
// POST: /Opportunities/Edit/5
[HttpPost]
public ActionResult Edit(OpportunityModel opportunity)
{
logger.Debug(">>Edit(GET)");
try
{
if (ModelState.IsValid)
{
//TownBL.UpdateMultiShop(multishop);
logger.InfoFormat("Opportunity {0} Updates", opportunity.Name);
}
TempData["Sucess"] = "Opportunity Sucessfully Updated";
return RedirectToAction("Index");
}
catch (Exception ex)
{
logger.Error(ex);
TempData["Warnning"] = "Error Updating Opportunity";
return View();
}
finally
{
logger.Debug("<<Edit(POST)");
}
}
//
// GET: /Opportunities/Delete/5
//public ActionResult Delete(Guid GuidId)
//{
// logger.Debug(">>Delete(GET)");
// try
// {
// //MultiShops opportunity = TownBL.getMultishops().Single(m => m.ID == id);
// TempData["Sucess"] = "Opportunity Sucessfully Deleted";
// //return View(opportunity);
// }
// catch (Exception ex)
// {
// logger.Error(ex);
// TempData["Warnning"] = "Error Deletting Opportunity";
// return View("Index");
// }
// finally
// {
// logger.Debug("<<Delete(GET)");
// }
//}
//
// POST: /Opportunities/Delete/5
[HttpPost]
public ActionResult Delete(OpportunityModel opportunity)
{
logger.Debug(">>Delete(POST)");
try
{
//TownBL.DeleteMultiShop(multishop.ID);
logger.InfoFormat("{0} Opportunity Deleted", opportunity.Name);
return RedirectToAction("Index");
}
catch (Exception ex)
{
logger.Error(ex);
return View();
}
finally
{
logger.Debug("<<Delete(POST)");
}
}
}
}
My Model:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace SaasSocialNetwork.Models
{
public class OpportunityModel
{
public Guid GuidID { get; set; }
[Required(ErrorMessage = "Enter ID")]
[StringLength(50)]
[RegularExpression("^[0-9a-zA-Z ]+$", ErrorMessage = "ID must be alphanumeric")]
public string Id { get; set; }
[Required(ErrorMessage = "Enter Name")]
[StringLength(50)]
[RegularExpression("^[0-9a-zA-Z ]+$", ErrorMessage = "Name must be alphanumeric")]
public string Name { get; set; }
[Required(ErrorMessage = "Enter Network ID")]
[StringLength(50)]
[RegularExpression("^[0-9a-zA-Z ]+$", ErrorMessage = "ID must be alphanumeric")]
public string NetworkId { get; set; }
[Required(ErrorMessage = "Enter Description")]
public string Description { get; set; }
[Required(ErrorMessage = "Enter image URL")]
public string ImageUrl { get; set; }
/// <summary>
/// This is the name of the organization
/// </summary>
[Required(ErrorMessage = "Enter the organization name")]
[StringLength(50)]
[RegularExpression("^[0-9a-zA-Z ]+$", ErrorMessage = "Name must be alphanumeric")]
public string Organization { get; set; }
}
}
And the view I wish to populate:
#model IEnumerable<SaasSocialNetwork.Models.OpportunityModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.GuidID)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.NetworkId)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.ImageUrl)
</th>
<th>
#Html.DisplayNameFor(model => model.Organization)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.GuidID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.NetworkId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.ImageUrl)
</td>
<td>
#Html.DisplayFor(modelItem => item.Organization)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>

Related

Returning array or List of models from form in Razor View to action on Submit

I am working on a learning project in which I created a view which displays a list of Delisted Books( isActive = false) populated by calling an api.
The view has a list of books + a checkbox in front of each book so that upon clicking the books we want to set active and hit the save button, it returns the books which are selected to the action in controller.
This is the view I am working with :
#model IEnumerable<MvcBooksList.Models.Book>
#{
ViewData["Title"] = "Delisted Books";
}
#if (Model != null)
{
#using (Html.BeginForm("DelistedForm", "Book", FormMethod.Post, new { #id = "myForm" }))
{
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.BookName)
</th>
<th>
#Html.DisplayNameFor(model => model.Author)
</th>
<th>
#Html.DisplayNameFor(model => model.Publisher)
</th>
<th>
Enlist
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.BookName)
#Html.HiddenFor(modelItem => item.BookName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Author)
#Html.HiddenFor(modelItem => item.Author)
</td>
<td>
#Html.DisplayFor(modelItem => item.Publisher)
#Html.HiddenFor(modelItem => item.Publisher)
</td>
<td>
#Html.CheckBoxFor(modelItem => item.IsActive)
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Save" /> <input type = "button" value = "Cancel" onclick = "location.href='#Url.Action("Index", "Home")'" />
}
}
else
{
<h3>No Books currently delisted</h3>
}
This is the model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MvcBooksList.Models
{
public class Book
{
public string BookName { get; set; }
public string Author { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
public string Publisher { get; set; }
public bool IsActive { get; set; }
public double? Price { get; set; }
public int Pages { get; set; }
public string AddedBy { get; set; }
public string ModifiedBy { get; set; }
public DateTime AddedOn { get; set; }
public DateTime LastModifiedOn { get; set; }
}
}
and this is the controller:
[HttpPost]
public async Task<ActionResult> DelistedForm(IEnumerable<Book> fromDelist)
{
foreach (var item in fromDelist)
{
if (item.IsActive == true)
//CALL
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = baseAddressOfBookApi;
var resopnse = await client.GetAsync("Book/EnlistBook?id="+item.BookName.ToString());
if (!resopnse.IsSuccessStatusCode)
{
return View(null);
}
}
}
}
return RedirectToAction("Index","Home");
}
Dont mind the code inside the action.
So when I press the submit button nothing gets passed to the action. The fromDelist collection is showing a count of 0.
So ,what am I doing wrong.
And Is it possible that I can return the names of books that are checked.
BookController ::
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MvcBooksList.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace MvcBooksList.Controllers
{
public class BookController : Controller
{
readonly Uri baseAddressOfBookApi;
public BookController(IConfiguration configuration)
{
baseAddressOfBookApi = new Uri(configuration.GetSection("ApiAddress:BookAPI").Value);
}
/*
public ActionResult Edit(string name)
{
return View(name); //repalce with the name of view
}
public ActionResult Delete(string name)
{
return View(name); //repalce with the name of view
}
public ActionResult Delist(string name)
{
return View(name); //repalce with the name of view
}
*/
public async Task<ActionResult> ViewDelistedBooks()
{
List<Book> bookdetails = new List<Book>();
using (HttpClient client = new HttpClient())
{
client.BaseAddress = baseAddressOfBookApi;
var response = await client.GetAsync("Book/ViewDelistedBooks");
if (response.IsSuccessStatusCode)
{
var BookResponse = response.Content.ReadAsStringAsync().Result;
bookdetails = JsonConvert.DeserializeObject<List<Book>>(BookResponse);
}
}
return View(bookdetails);
}
public ActionResult Cancel()
{
return View("~/Views/Home/Index.cshtml");
}
[HttpPost]
public async Task<ActionResult> DelistedForm(IEnumerable<Book> fromDelist)
{
foreach (var item in fromDelist)
{
if (item.IsActive == true)
//CALL
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = baseAddressOfBookApi;
var resopnse = await client.GetAsync("Book/EnlistBook?id="+item.BookName.ToString());
if (!resopnse.IsSuccessStatusCode)
{
return View(null);
}
}
}
}
return RedirectToAction("Index","Home");
}
}
}
Try to replace foreach by for
#model List<MvcBooksList.Models.Book>
#for (int i = 0; i < Model.Count(); i+=1)
{
......
<td>
#Html.DisplayFor(model=> model[i].Publisher)
#Html.HiddenFor(model => model[i].Publisher)
</td>
<td>
#Html.CheckBoxFor(model => model[i].IsActive)
</td>
</tr>
.... and so on for all
and replace a table header
<th>
#Html.DisplayNameFor(model => model[0].BookName)
</th>
<th>
#Html.DisplayNameFor(model => model[0].Author)
</th>

Parent-Child model (multiple model) in one view (ASP.NET Core (C#) + MVC + Entity Framework)

I am trying to make a Web App which has Parent-Child model (multiple model) in one view (ASP.NET Core + MVC + Entity Framework).
The following is input (input No.1).
This is "Views/Blogs/index.cshtml"
The following is also input (input No.2).
This is "Views/Tags/index.cshtml"
The following is my expecting output (output No.1).
I have written the following "Views/Blogs/cshtml".
#model IEnumerable<urlapp12.Models.UrlTag>
#{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Blog.Userid)
</th>
<th>
#Html.DisplayNameFor(model => model.Blog.Url)
</th>
<th>
#Html.DisplayNameFor(model => model.Blog.LastUpdatedAt_UtcDt)
</th>
<th>
#Html.DisplayNameFor(model => model.Blog.LastUpdatedAt_LocalDt)
</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Blog.Userid)
</td>
<td>
#Html.DisplayFor(modelItem => item.Blog.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Blog.LastUpdatedAt_UtcDt)
</td>
<td>
#Html.DisplayFor(modelItem => item.Blog.LastUpdatedAt_LocalDt)
</td>
<td>
#foreach (var childItem in item.Tag)
{
#Html.DisplayFor(modelItem => childItem.tagItem)
}
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Blog.BlogId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Blog.BlogId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Blog.BlogId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
And executed, I have gotten the following error.
(output No.2. The real unexpected output)
An unhandled exception occurred while processing the request.
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1[urlapp12.Models.Blog]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[urlapp12.Models.UrlTag]'.
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(object value)
Models/Blog.cs is the following.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace urlapp12.Models
{
public partial class Blog
{
public Blog()
{
Post = new HashSet<Post>();
}
[Key]
public int BlogId { get; set; }
public string Userid { get; set; }
public string Url { get; set; }
public string Title { get; set; }
public string CreatedBy { get; set; }
[System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
public DateTime CreatedAt_UtcDt { get; set; }
[System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
public DateTime CreatedAt_LocalDt { get; set; }
public string LastUpdatedBy { get; set; }
[System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
public DateTime LastUpdatedAt_UtcDt { get; set; }
[System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
public DateTime LastUpdatedAt_LocalDt { get; set; }
public ICollection<Tag> Tag { get; set; }
public ICollection<Post> Post { get; set; }
/*
public List<Tag> Tag { get; set; }
public List<Post> Post { get; set; }
*/
}
}
Models/Tag.cs is the following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace urlapp12.Models
{
public class Tag
{
public int Id { get; set; }
public int DispOrderNbr { get; set; }
public string tagItem { get; set; }
public int BlogId { get; set; }
public string CreatedBy { get; set; }
[System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
public DateTime CreatedAt_UtcDt { get; set; }
[System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
public DateTime CreatedAt_LocalDt { get; set; }
public string LastUpdatedBy { get; set; }
[System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
public DateTime LastUpdatedAt_UtcDt { get; set; }
[System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
public DateTime LastUpdatedAt_LocalDt { get; set; }
[System.ComponentModel.DataAnnotations.Schema.ForeignKey("BlogId")]
public Blog blog { get; set; }
}
}
Model/UlrTag.cs is the following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace urlapp12.Models
{
public class UrlTag
{
public Blog Blog { get; set; }
public IEnumerable<Tag> Tag { get; set; }
}
}
Does someone help about this Parent-Child model?
Thank you in advance.
Blogs.Controller.cs is the following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using urlapp12.Models;
namespace urlapp12.Controllers
{
public class BlogsController : Controller
{
private readonly Blogging02Context _context;
// Stores UserManager
private readonly UserManager<ApplicationUser> _manager;
private UserManager<ApplicationUser> _userManager;
public BlogsController(Blogging02Context context, UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
_context = context;
}
// GET: Blogs
public async Task<IActionResult> Index()
{
return View(await _context.Blog.ToListAsync());
}
// GET: Blogs/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var blog = await _context.Blog
.SingleOrDefaultAsync(m => m.BlogId == id);
if (blog == null)
{
return NotFound();
}
return View(blog);
}
// GET: Blogs/Create
public IActionResult Create()
{
return View();
}
// POST: Blogs/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost] [ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("BlogId,Userid,Url,Title")] Blog blog)
{
if (ModelState.IsValid)
{
/*
string strCurrentUserId;
strCurrentUserId = User.Identity.GetUserId(this IIdentity identity);
var currentUserName = User.Identity.Name ;
var user = await UserManager<ApplicationUser>.FindByIdAsync(User.Identity.GetUserId());
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new MyDbContext()));
var UserManager = new UserManager(IUserstore<ApplicationUser>);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var user = await GetCurrentUserAsync();
var userId = user?.Id;
string mail = user?.Email;
var userid = GetCurrentUserClaims().userid;
var userClaims = new UserClaims();
var claims = _httpContextAccessor.HttpContext.User.Claims.ToList();
var userid2 = await IGenericRepository < User > userRepository.GetByIdAsync(_currentUserGuid);
UserManager<ApplicationUser> _userManager;
SignInManager<ApplicationUser> _signInManager = new SignInManager<ApplicationUser>();
var info = await _signInManager.GetExternalLoginInfoAsync();
*/
// Stores UserManager
// private readonly UserManager<ApplicationUser> _manager;
// var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
// var result = await _userManager.CreateAsync(user, model.Password);
var user = await _userManager.GetUserAsync(HttpContext.User);
var currentLoginUserid = user.Id;
blog.Userid = user.Id;
int maxIdInDb = 0;
int BlogRecCnt = _context.Blog.Count();
if (_context.Blog.Count() == 0)
{
maxIdInDb = 0;
}
else
{
maxIdInDb = _context.Blog.Max(p => p.BlogId);
}
int NextId = maxIdInDb + 1;
blog.BlogId = NextId;
blog.CreatedAt_LocalDt = DateTime.Now;
blog.CreatedAt_UtcDt = DateTime.UtcNow;
blog.CreatedBy = user.Id;
blog.LastUpdatedAt_LocalDt = DateTime.Now;
blog.LastUpdatedAt_UtcDt = DateTime.UtcNow;
blog.LastUpdatedBy = user.Id;
_context.Add(blog);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(blog);
}
// GET: Blogs/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var blog = await _context.Blog.SingleOrDefaultAsync(m => m.BlogId == id);
if (blog == null)
{
return NotFound();
}
var user = await _userManager.GetUserAsync(HttpContext.User);
var currentLoginUserid = user.Id;
blog.Userid = user.Id;
blog.LastUpdatedAt_LocalDt = DateTime.Now;
blog.LastUpdatedAt_UtcDt = DateTime.UtcNow;
blog.LastUpdatedBy = user.Id;
return View(blog);
}
// POST: Blogs/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("BlogId,Userid,Url,Title")] Blog blog)
{
if (id != blog.BlogId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(blog);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BlogExists(blog.BlogId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(blog);
}
// GET: Blogs/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var blog = await _context.Blog
.SingleOrDefaultAsync(m => m.BlogId == id);
if (blog == null)
{
return NotFound();
}
return View(blog);
}
// POST: Blogs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var blog = await _context.Blog.SingleOrDefaultAsync(m => m.BlogId == id);
_context.Blog.Remove(blog);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool BlogExists(int id)
{
return _context.Blog.Any(e => e.BlogId == id);
}
}
}
TagsController.cs is the following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using urlapp12.Models;
namespace urlapp12.Controllers
{
public class TagsController : Controller
{
private readonly Blogging02Context _context;
public TagsController(Blogging02Context context)
{
_context = context;
}
//int id, [Bind("BlogId,Userid,Url,Title")] Blog blog
// GET: Tags
// public async Task<IActionResult> Index()
public async Task<IActionResult> Index(int id, [Bind("BlogId,Userid,Url,Title")] Blog blog)
{
/*
return View(await _context.Tag.ToListAsync());
*/
var blogging02Context = _context.Tag.Include(t => t.blog);
return View(await blogging02Context.ToListAsync());
// return View (await _context.Tag.ToListAsync());
}
// GET: Tags/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var tag = await _context.Tag
.Include(t => t.blog)
.SingleOrDefaultAsync(m => m.Id == id);
if (tag == null)
{
return NotFound();
}
return View(tag);
}
// GET: Tags/Create
public IActionResult Create()
{
ViewData["BlogId"] = new SelectList(_context.Blog, "BlogId", "Title");
return View();
}
// POST: Tags/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,DispOrderNbr,tagItem,BlogId")] Tag tag)
{
if (ModelState.IsValid)
{
_context.Add(tag);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["BlogId"] = new SelectList(_context.Blog, "BlogId", "Title", tag.BlogId);
return View(tag);
}
// GET: Tags/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var tag = await _context.Tag.SingleOrDefaultAsync(m => m.Id == id);
if (tag == null)
{
return NotFound();
}
ViewData["BlogId"] = new SelectList(_context.Blog, "BlogId", "Title", tag.BlogId);
return View(tag);
}
// POST: Tags/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,DispOrderNbr,tagItem,BlogId")] Tag tag)
{
if (id != tag.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(tag);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TagExists(tag.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["BlogId"] = new SelectList(_context.Blog, "BlogId", "Title", tag.BlogId);
return View(tag);
}
// GET: Tags/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var tag = await _context.Tag
.Include(t => t.blog)
.SingleOrDefaultAsync(m => m.Id == id);
if (tag == null)
{
return NotFound();
}
return View(tag);
}
// POST: Tags/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int? id)
{
var tag = await _context.Tag.SingleOrDefaultAsync(m => m.Id == id);
_context.Tag.Remove(tag);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool TagExists(int id)
{
return _context.Tag.Any(e => e.Id == id);
}
}
}
junkangli and Gimly, thank you for reply.
I have tried the Gimly's idea.
public async Task<IActionResult> Index()
{
return View(await _context.Blog.Include(b => b.Tags).ToListAsync());
}
Then Visual Studio told me that "'Blog' does not include 'Tags' definition" error.
So I have changed Tags to Tag, My Visual Studio says it is O.K.
public async Task<IActionResult> Index()
{
return View(await _context.Blog.Include(b => b.Tag).ToListAsync());
}
I run my codes for Debug mode, the web application returned the following error.
An unhandled exception occurred while processing the request.
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List1[urlapp12.Models.Blog]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable1[urlapp12.Models.UrlTag]'.
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(object value)
Thank you very much.
I have changed the code "/Views/Blogs/Index.cshml" like the following, and I could execute it successfully.
#model IEnumerable<urlapp12.Models.Blog>
#{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Userid)
</th>
<th>
#Html.DisplayNameFor(model => model.Url)
</th>
<th>
#Html.DisplayNameFor(model => model.LastUpdatedAt_UtcDt)
</th>
<th>
#Html.DisplayNameFor(model => model.LastUpdatedAt_LocalDt)
</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Userid)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastUpdatedAt_UtcDt)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastUpdatedAt_LocalDt)
</td>
<td>
#foreach (var childItem in item.Tag)
{
#Html.DisplayFor(itemItem => childItem.tagItem)
}
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.BlogId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.BlogId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.BlogId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
First, about the exception you're getting, the error message is pretty explicit, and #junkangli explained it will in its comment, you're not returning the correct object to the View. View expects an IEnumerable<UrlTag> and you're sending it an IEnumerable<Blog>.
Now, about the core of your issue, you'll want to load the list of tags in your query for getting the list of Blogs, so, in your controller's Index action, you should do something like:
public async Task<IActionResult> Index()
{
return View(await _context.Blog.Include(b => b.Tags).ToListAsync());
}
Then, in your view, you should be able to access your tags and create a while loop to display all your tags.

Invalid object name 'dbo.TableName' ASP

I looked everywhere and I can't figure out what the problem is with my asp project.
Basically I get this error
Invalid object name dbo.Enquires.
It's looking for a table which doesn't exist, and I never mention that table anywhere, not sure why it's looking for it.
EnquireController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using System.Net;
using PetePersonalTrainerFinal.Models;
namespace PetePersonalTrainerFinal.Controllers
{
public class EnquireController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
[Authorize(Roles ="Admin, Mod")]
// Enquire
public ActionResult Index(string SearchName)
{
var items = from i in db.Enquiries select i;
if (!String.IsNullOrEmpty(SearchName))
{
items = items.Where(i => i.Name.Contains(SearchName));
}
return View(items);
}
[Authorize(Roles ="Admin, Mod")]
// Details
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Enquire enquire = db.Enquiries.Find(id);
if (enquire == null)
{
return HttpNotFound();
}
return View(enquire);
}
// Create
public ActionResult Create()
{
return View();
}
// Post Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create ([Bind(Include ="Id,Name,Address,Suburb,State,Postcode,Email,Phone,Description")] Enquire enquire)
{
if (ModelState.IsValid)
{
db.Enquiries.Add(enquire);
db.SaveChanges();
TempData["message"] = "Your enquiry has been successufully submitted.";
return RedirectToAction("Index", "Home");
}
return View(enquire);
}
// Edit
[Authorize(Roles = "Admin")]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Enquire enquire = db.Enquiries.Find(id);
if (enquire == null)
{
return HttpNotFound();
}
return View(enquire);
}
//Post edit
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public ActionResult Edit([Bind(Include = "Id,Name,Address,Suburb,State,Postcode,Email,Phone,Description")] Enquire enquire)
{
if (ModelState.IsValid)
{
db.Enquiries.Add(enquire);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(enquire);
}
// Delete
[Authorize(Roles = "Admin")]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Enquire enquire = db.Enquiries.Find(id);
if (enquire == null)
{
return HttpNotFound();
}
return View(enquire);
}
// Post Delete
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public ActionResult DeleteConfirmed(int id)
{
Enquire enquire = db.Enquiries.Find(id);
db.Enquiries.Remove(enquire);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Enquire.cs Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace PetePersonalTrainerFinal.Models
{
public class Enquire
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
[Display(Name = "Name")]
public string Name { get; set; }
[Required(ErrorMessage = "Address is required")]
[Display(Name = "Address")]
public string Address { get; set; }
[Required(ErrorMessage = "Suburb is required")]
[Display(Name = "Suburb")]
public string Suburb { get; set; }
[Required(ErrorMessage = "State is required")]
[Display(Name = "State")]
public string State { get; set; }
[Required(ErrorMessage = "Postcode is required")]
[Display(Name = "Postcode")]
public string Postcode { get; set; }
[Required(ErrorMessage = "Email is required")]
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Phone is required")]
[Display(Name = "Phone")]
public string Phone { get; set; }
[Required(ErrorMessage = "Description is required")]
[Display(Name = "Description")]
public string Description { get; set; }
}
}
And that is The Page I get the error on.
#model IEnumerable<PetePersonalTrainerFinal.Models.Enquire>
#{
ViewBag.Title = "Index";
}
<div class="container">
<h2>Index</h2>
#if (User.IsInRole("Admin"))
{
<p>
#Html.ActionLink("Create New", "Create")
</p>
}
#if (User.IsInRole("Admin") || User.IsInRole("Mod"))
{
using (Html.BeginForm())
{
<p>
Name: #Html.TextBox("SearchName")
<input type="submit" value="Search" />
</p>
}
}
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Suburb)
</th>
<th>
#Html.DisplayNameFor(model => model.State)
</th>
<th>
#Html.DisplayNameFor(model => model.Postcode)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>
#Html.DisplayNameFor(model => model.Phone)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.Suburb)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td>
#Html.DisplayFor(modelItem => item.Postcode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.ActionLink("Update", "Edit", new { id = item.Id}) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
For some reason I keep getting the error and I can't seem to fix it. I don't have much experience with asp.net. Here is the error I get http://pastebin.com/Gmmhn0VX
It keeps looking for dbo.Enquires and that doesn't exist, I also searched the whole project and I can't see anywhere that something refers to dbo.Enquires.
Any help would be appreciated.
Edit: Here is the ApplicationDBContext
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace PetePersonalTrainerFinal.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/? LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public System.Data.Entity.DbSet<PetePersonalTrainerFinal.Models.Price> Prices { get; set; }
public System.Data.Entity.DbSet<PetePersonalTrainerFinal.Models.Enquire> Enquiries { get; set; }
}
}
Decorating Enquire Model class with [Table("Enquiries")] fixed the issue.
Credits to Ajinder Singh.

Variables from one table display along side another in the view

Hi there I was looking for a way to select certain fields from the different database tables and output it into one table in the view.This is the code I have so far although it is only able to retrieve information from the patients table. Any help would be greatly appreciated thanks.
model
namespace ChampPMS.Models
{
public class Patient
{
public int PatientID { get; set; }
public string HouseChartNo { get; set; }
public string ClinicChartNo { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public DateTime DOB { get; set; }
Dont think this is right.
//Other Table variables
public Admission ExpectedDate { get; set; } ------->from bed
public Beds Bed { get; set; } ------->from admissions
}
public class Beds
{
public int BedID { get; set; }
public int RoomID { get; set; }
public string Bed { get; set; }
}
public class Admission
{
public int AdmissionID { get; set; }
public int PatientID { get; set; }
public DateTime ExpectedDate { get; set; }
public int BedID { get; set; }
public string Phone { get; set; }
}
public PatientDBContext()
: base("PatientsDBContext")//connection string
{
}
public DbSet<Admission> Admission { get; set; }
public DbSet<Beds> Beds { get; set; }
public DbSet<Patient> Patient { get; set; }
}
view
#model IEnumerable<ChampPMS.Models.Patient>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create", null, new { #class = "btn btn-success" })
</p>
<table class="table table-condensed table-striped table-hover table-bordered ">
<tr>
<th>
#Html.DisplayNameFor(model => model.HouseChartNo)
</th>
<th>
#Html.DisplayNameFor(model => model.ClinicChartNo)
</th>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
#Html.DisplayNameFor(model => model.DOB)
</th>
<th>
#Html.DisplayNameFor(model => model.Bed)----->from bed table
</th>
<th>
#Html.DisplayNameFor(model => model.ExpectedDate)----->from admission table
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.HouseChartNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.ClinicChartNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.SurName)
</td>
<td>
#Html.DisplayFor(modelItem => item.DOB)
</td>
<td>
#Html.DisplayNameFor(model => model.Bed)------->from bed table
</td>
<td>
#Html.DisplayNameFor(model => model.ExpectedDate) ----->from admission table
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.PatientID }, new { #class = "btn btn-xs btn-info" }) |
#Html.ActionLink("Details", "Details", new { id = item.PatientID }, new { #class = "btn btn-xs btn-primary" }) |
#Html.ActionLink("Delete", "Delete", new { id = item.PatientID }, new { #class = "btn btn-xs btn-danger" })
</td>
</tr>
}
</table>
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 ChampPMS.Models;
namespace ChampPMS.Controllers
{
public class PatientsController : Controller
{
private PatientDBContext db = new PatientDBContext();
// GET: Patients
public ActionResult Index()
{
return View(db.Patient.ToList());
}
// GET: Patients/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Patient patient = db.Patient.Find(id);
if (patient == null)
{
return HttpNotFound();
}
return View(patient);
}
// GET: Patients/Create
public ActionResult Create()
{
return View();
}
// POST: Patients/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PatientID,HouseChartNo,ClinicChartNo,Title,FirstName,SurName,DOB,HouseName,Street,Town,County,Telephone,Mobile,Gender,Occupation,Marital,TaxNumber,GMSnumber,DPSnumber,ReligionID,Status,HashCode")] Patient patient)
{
if (ModelState.IsValid)
{
db.Patient.Add(patient);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(patient);
}
// GET: Patients/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Patient patient = db.Patient.Find(id);
if (patient == null)
{
return HttpNotFound();
}
return View(patient);
}
// POST: Patients/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PatientID,HouseChartNo,ClinicChartNo,Title,FirstName,SurName,DOB,HouseName,Street,Town,County,Telephone,Mobile,Gender,Occupation,Marital,TaxNumber,GMSnumber,DPSnumber,ReligionID,Status,HashCode")] Patient patient)
{
if (ModelState.IsValid)
{
db.Entry(patient).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(patient);
}
// GET: Patients/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Patient patient = db.Patient.Find(id);
if (patient == null)
{
return HttpNotFound();
}
return View(patient);
}
// POST: Patients/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Patient patient = db.Patient.Find(id);
db.Patient.Remove(patient);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Rather than return the data directly from the database to the View you should create a View-Model in the controller action.
This ViewModel would contain all of the information that you need to display.
Using a ViewModel ensures that only the data required for the View is returned. It means rendering your View is more simple and you can use data from many different sources in one single ViewModel.

Paging In MVC Table Grid

What I am trying to achieve is to include paging functionality in a grid (generated with an html table and a foreach statement).
I am not allowed to use entity framework, webgrid, or any other third party grid.
Below are the details of my task:
DemoTestData.cs file
namespace Demo.Data
{
public class DemoTestData
{
DemoTestModel objdemoTestModel = null;
public string connectionString { get; set; }
public SqlConnection objConnection { get; set; }
public SqlCommand objCommand { get; set; }
public SqlDataReader objReader { get; set; }
public List<DemoTestModel> GetAllDemoTest()
{
List<DemoTestModel> listDemoTest = new List<DemoTestModel>();
try
{
objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
objConnection.Open();
objCommand = new SqlCommand("sp_DemoTest", objConnection);
objCommand.CommandType = System.Data.CommandType.StoredProcedure;
objReader = objCommand.ExecuteReader();
if (objReader.HasRows)
{
while (objReader.Read())
{
// list will be populated here.
objdemoTestModel = new DemoTestModel();
objdemoTestModel.Id = Convert.ToInt32(objReader["Id"].ToString());
objdemoTestModel.Column1 = objReader["Column1"].ToString();
objdemoTestModel.Column2 = objReader["Column2"].ToString();
objdemoTestModel.Column3 = objReader["Column3"].ToString();
objdemoTestModel.Column4 = objReader["Column4"].ToString();
objdemoTestModel.Column5 = objReader["Column5"].ToString();
objdemoTestModel.Column6 = objReader["Column6"].ToString();
listDemoTest.Add(objdemoTestModel);
}
//return listStateModel;
}
}
catch (Exception ex)
{
string m = ex.Message;
}
finally
{
if (objConnection != null)
{
objConnection.Close();
}
}
return listDemoTest;
}
}
}
sp_DemoTest procedure
CREATE PROCEDURE [dbo].[sp_DemoTest]
AS
BEGIN
select Id,Column1,Column2,Column3,Column4,Column5,Column6 from dbo.DemoTest
END
DemoTestModel.cs file
namespace Demo.Entities
{
public class DemoTestModel
{
public int Id { get; set; }
public string Column1 { get; set; }
public string Column2 { get; set; }
public string Column3 { get; set; }
public string Column4 { get; set; }
public string Column5 { get; set; }
public string Column6 { get; set; }
}
}
DemoTestController.cs file
namespace SampleProject.Controllers
{
public class DemoTestController : Controller
{
// GET: /DemoTest/
//Test tst = new Test();
DemoTestData data = new DemoTestData();
//List<CountryModel> ListModel = new List<CountryModel>();
List<DemoTestModel> ListModel = new List<DemoTestModel>();
//DemoTestModel demoTestModel = new DemoTestModel();
public ActionResult Index()
{
ListModel = data.GetAllDemoTest();
return View(ListModel);
}
}
}
Index.cshtml file
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Column1)
</th>
<th>
#Html.DisplayNameFor(model => model.Column2)
</th>
<th>
#Html.DisplayNameFor(model => model.Column3)
</th>
<th>
#Html.DisplayNameFor(model => model.Column4)
</th>
<th>
#Html.DisplayNameFor(model => model.Column5)
</th>
<th>
#Html.DisplayNameFor(model => model.Column6)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#if (item.Column1 == "Textbox")
{
#Html.TextBoxFor(modelItem => item.Column1)
}
else if (item.Column1 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column1, Enumerable.Empty<SelectListItem>())
}
else
{
#Html.DisplayFor(modelItem => item.Column1)
}
</td>
<td>
#if (item.Column2 == "Textbox")
{
#Html.TextBoxFor(modelItem => item.Column2)
}
else if (item.Column2 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column2, Enumerable.Empty<SelectListItem>())
}
else
{
#Html.DisplayFor(modelItem => item.Column2)
}
<td>
#if (item.Column3 == "Textbox")
{
#Html.TextBoxFor(modelItem => item.Column3)
}
else if (item.Column3 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column3, Enumerable.Empty<SelectListItem>())
}
else
{
#Html.DisplayFor(modelItem => item.Column3)
}
</td>
<td>
#if (item.Column4 == "Textbox")
{
#Html.TextBox("test", "", new { style = "width:130px;" })
}
else if (item.Column4 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column4, Enumerable.Empty<SelectListItem>())
}
else
{
#Html.DisplayFor(modelItem => item.Column4)
}
</td>
<td>
#if (item.Column5 == "Textbox")
{
#Html.TextBox("test1", "", new { style = "width:130px;" })
}
else if (item.Column5 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column5, Enumerable.Empty<SelectListItem>(), new { style = "width: 130px" })
}
else
{
#Html.DisplayFor(modelItem => item.Column5)
}
</td>
<td>
#if (item.Column6 == "Textbox")
{
#Html.TextBoxFor(modelItem => item.Column6)
}
else if (item.Column6 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column6, Enumerable.Empty<SelectListItem>())
}
else
{
#Html.DisplayFor(modelItem => item.Column6)
}
</td>
</tr>
}
</table>
(if..else condition is used to generate dynamic controls)
This is the rendered view
It would be very nice if anyone could provide a solution.

Categories

Resources