How can I send to view a DTO and Model - asp.net-mvc

My Dto
public class homePageDTO
{
public IEnumerable<Yazi> yazi { get; set; }
public IEnumerable<Yorum> yorum { get; set; }
}
My ActionMethod
public ActionResult Post(int pid)
{
homePageDTO obj = new homePageDTO();
obj.yazi = ent.Yazi.Where(x=>(x.YaziID==(int)pid)).ToList();
obj.yorum = ent.Yorum.Where(x => (x.YorumNo == (int)pid)).ToList();
return View(obj);
}
My multi model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication15.Models
{
public class BigViewModel
{
public homePageDTO home { get; set; }
public Yorum Yorrum { get; set; }
}
}
My View
#model WebApplication15.Models.BigViewModel
#{
ViewBag.Title = "Post";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#foreach (var item in Model.home.yazi)
{
<header class="intro-header" style="background-image: url('/content/img/post-bg.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="site-heading">
<h1>#item.YaziUstBaslik</h1>
<hr class="small">
<span class="subheading"><b>#item.YaziAltBaslik</b></span>
</div>
</div>
</div>
</div>
</header>
<!-- Post Content -->
<article>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p>#item.Yazi1</p>
<p class="alert alert-warning">Yollayan #item.YazarKullaniciAdi-#item.YaziTarih</p>
</div>
</div>
</div>
</article>
<hr>
}
<h2>Index</h2>
<table class="table">
<tr>
<th>
Yorum
</th>
<th>
Yorum Sahibi
</th>
<th>
Tarihi
</th>
<th></th>
</tr>
#foreach (var x in Model.home.yorum)
{
<tr>
<td>
#x.Yorum1
</td>
<td>
#x.YorumSahibi
</td>
<td>
#x.YorumTarihi
</td>
</tr>
}
</table>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Yeni Yorum</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Selam</h4>
</div>
<div class="modal-body">
<p>nasdsadasdasda</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Yolla</button>
</div>
</div>
</div>
</div>
</div>
ERROR
The model item passed into the dictionary is of type 'WebApplication15.Models.homePageDTO', but this dictionary requires a model item of type 'WebApplication15.Models.BigViewModel'.
It was dissolved
My new action method
public ActionResult Post(int pid)
{
BigViewModel bigyorum = new BigViewModel();
bigyorum.home = new homePageDTO();
bigyorum.home.yazi = ent.Yazi.Where(x=>(x.YaziID==(int)pid)).ToList();
bigyorum.home.yorum = ent.Yorum.Where(x => (x.YorumNo == (int)pid)).ToList();
return View(bigyorum);
}

you need to change the model that is related in the view, in the first line of the view set this:
#model WebApplication15.Models.homePageDTO
I think homePageDTO is in the namespace WebApplication15.Models, if not, put the correct namespace.
With your update:
In your action, you are passing an object of type homePageDTO:
public ActionResult Post(int pid)
{
homePageDTO obj = new homePageDTO();
obj.yazi = ent.Yazi.Where(x=>(x.YaziID==(int)pid)).ToList();
obj.yorum = ent.Yorum.Where(x => (x.YorumNo == (int)pid)).ToList();
return View(obj);
}
and in your view, yo have:
#model WebApplication15.Models.BigViewModel
There are differents objects, the type of the object that you pass from the action to the view, must be the same that you declare in the view.
So, change the action to return a BigViewModel or change in your view to homePageDTO

Related

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1 .

Welcome,
I have several pictures, when I click on one it should take me to another window of this picture.
But this does not happen, but I get this window with this error message:
The model item passed into the dictionary is of type
'System.Collections.Generic.List`1[FirstProject.Models.student]', but
this dictionary requires a model item
I will put the codes related to the problem:
HomeController
using FirstProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FirstProject.Controllers
{
public class HomeController : Controller
{
level_8_coursesEntities db = new level_8_coursesEntities();
public ActionResult Index()
{
List<level_8_courses> list = db.level_8_courses.ToList();
return View(list);
}
public ActionResult Numberofstudents()
{
List<level_8_courses> list = db.level_8_courses.ToList();
return View(list);
}
public ActionResult Students(int? id)
{
List<student> studentlist = null;
if (id.HasValue)
{
studentlist = db.students.Where(x => x.corId == id).ToList();
}
else
{
// Set the `studentlist` to some default value when `id` doesn't defined or not a number.
studentlist = null;
}
return View(studentlist);
}
Number of students.chtml
#{
ViewBag.Title = "Numberofstudents";
}
#using FirstProject.Models;
#model List<level_8_courses>
<div class="container">
<section class="page-section portfolio" id="portfolio">
<div class="container">
<!-- Portfolio Section Heading-->
<h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Numberofstudents</h2>
<!-- Icon Divider-->
<div class="divider-custom">
<div class="divider-custom-line"></div>
<div class="divider-custom-icon"><i class="fas fa-star"></i></div>
<div class="divider-custom-line"></div>
</div>
<!-- Portfolio Grid Items-->
<div class="row justify-content-center">
<!-- Portfolio Item 1 data-bs-target="#portfolioModal" -->
#foreach (var item in Model)
{
<div class="col-md-6 col-lg-4 mb-5">
<a href="/Home/students/#item.Id">
<div class="portfolio-item mx-auto" data-bs-toggle="modal">
<div class="portfolio-item-caption d-flex align-items-center justify-content-center h-100 w-100">
<div class="portfolio-item-caption-content text-center text-white"><i class="fas fa-plus fa-3x"></i></div>
</div>
<img class="img-fluid" style="height:100px;width:100px" src="#item.photo" alt="" />
</div>
</a>
<div style="text-align:center">
<h5>#item.corName</h5>
</div>
</div>
}
</div>
</div>
</section>
</div>
Students.chtml
#using FirstProject.Models;
#model List<student>
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="card col-sm-6">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="..." alt="Card image cap">
<div class="card-body">
<h5 class="card-title">#item.sName</h5>
<p class="card-text">#item.sEmail</p>
</div>
</div>
</div>
}
</div>
</div>
Thanks
fix students action, if you don't have any students create an empty list as a model, and remove studentlist = null;
List<student> studentlist = null
if (id!=null && id > 0)
studentlist = db.students.Where(x => x.corId == id).ToList();
if(studentlist==null) studentslist= new List<student>();
return View(studentlist);

Calling a view from different models in ASP.NET MVC

In my ASP.NET MVC application in the view, I'm calling another view that is not related to the current model. There I need some help that how to call the different model views from another view.
#model Asp_PASMVC.Models.VehicleService
#using Asp_PASMVC.Infrastructure
#{
ViewBag.Title = "View";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> CompanyList = (List<SelectListItem>)TempData.Peek("ComapnyList");
List<SelectListItem> ReqTypes = (List<SelectListItem>)TempData.Peek("RequestTyleList");
List<SelectListItem> Employees = (List<SelectListItem>)TempData.Peek("EmployeeList");
List<SelectListItem> Location = (List<SelectListItem>)TempData.Peek("LocationList");
Asp_PASMVC.Models.AppRequest RequestDetails = (Asp_PASMVC.Models.AppRequest)TempData.Peek("RequestDetails");
}
#{
Html.RenderPartial("_MainRequestView", RequestDetails);
}
#using (Html.BeginForm("WorkshopUpdate", "VehicleService", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.Req_Id)
#Html.AntiForgeryToken()
if (Model != null && Model.VehicleServiceApproveDetails != null)
{
foreach (Asp_PASMVC.Models.VehicleServiceApproveDetails Emp in Model.VehicleServiceApproveDetails)
{
Html.RenderPartial("_WorkshopUpdate", Emp);
}
}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<!-- Default box -->
<div class="card">
<div class="card-header">
<h3 class="card-title">Approver Details</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="card-body">
<div>
<fieldset id="pnlApproverList" style="display:none">
<legend><h5>To whom you want to send this request for approval ? </h5> </legend>
<br />
<ul id="RequApprover" style="list-style-type: none">
#if (Model != null && Model.ApprovalPartyList != null)
{
foreach (Asp_PASMVC.Models.ApprovalParty Emp in Model.ApprovalPartyList)
{
Html.RenderPartial("_ApprovalView", Emp);
}
}
</ul>
<button type="button" id="addAnotherApprover" class="btn btn-success" href="#" onclick="this.style.display = 'none';">Add</button>
<script type="text/javascript">
$(function () {
// $("#movieEditor").sortable();
$("#addAnotherApprover").click(function () {
$.get('/VehicleService/AddApproverToReq', function (template) {
$("#RequApprover").append(template);
});
});
});
</script>
<br />
</fieldset>
</div>
</div>
<!-- /.card-footer-->
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
<div class="card-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update and Sent" class="btn btn-success" />
</div>
</div>
</div>
}
<p>
#Html.ActionLink("Back to List", "Index")
</p>
So likewise here the model is VehicleService. So within that view, I want to call another view that is not within the vehicleservice model.
But I cannot load that partial view within this view. Is there any way to do this?
#model Asp_PASMVC.Models.ApprovalParty
#using Asp_PASMVC.Infrastructure
#{
string UserLvel = TempData.Peek("UserLevelClaims").ToString();
}
<li style="padding-bottom:15px">
#using (Html.BeginCollectionItem("ApprovalPartyList"))
{
<div class="row">
<div class="col-md-5 col-sm-5">
<div class="form-group">
<label>
#Html.RadioButtonFor(m => m.Approve_Type, false)
<span class="radiomargin">For Manager</span>
</label>
<br />
#if (UserLvel != "1")
{
<label>
#Html.RadioButtonFor(m => m.Approve_Type, true)
<span class="radiomargin">For Top Manager </span>
</label>
#Html.ValidationMessageFor(model => model.Approve_Type, "", new { #class = "text-danger" })
}
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="form-group row">
Select the Approver
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Approver_Id, new List<SelectListItem>(), new { #id = "ddlEmployees", #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Approver_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
}
</li>
Create a ViewModel which can have both Properties and pass that viewmodel to View
Model class:
public class VehicleSerivceViewModel
{
public VehicleService VehicleService { get; set; }
public ApprovalParty ApprovalParty { get; set; }
}
In View :
#model Asp_PASMVC.Models.VehicleServiceVewModel
pass ViewModel to partial as below:
#Model.ApprovalParty

Binding List with checkbox and post back [duplicate]

This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 4 years ago.
I have a object that I am binding to my view. This object has a list of items with a boolean field on them. I use this boolean field to bind to a checkbox on the form. I am wanting the user to select the items they want and then submit. This issue is, when it is submitted and passed to the post action, the list of items is null.
Here is the View Model passed into the view.
public class ReAssignVM
{
public string ToUsername { get; set; }
public string FromUsername { get; set; }
public IEnumerable<ReAssignTaskVM> Tasks { get; set; }
} // End of Class
Here is the view:
#model SRM.ClassLibrary.V1.ViewModels.TaskViewModels.ReAssignVM
#{
ViewData["Title"] = "Re-Assign Tasks";
}
<h2>Re-Assign Tasks</h2>
<br />
<div class="row">
<div class="col-md-1 alignRight">
<b>From:</b>
</div>
<div class="col-md-3">
#Model.FromUsername
</div>
<div class="col-md-1 alignRight">
<b>To:</b>
</div>
<div class="col-md-3">
#Model.ToUsername
</div>
</div>
<br />
<form asp-action="ReAssignTasks">
<input type="hidden" asp-for="FromUsername" />
<input type="hidden" asp-for="ToUsername" />
<div include-if="#Model.Tasks != null && Model.Tasks.Count() > 0">
<table class="table table-hover">
<thead class="thead-light">
<tr>
<th></th>
<th>
Status
</th>
<th>
Date
</th>
<th>
Student
</th>
<th>
Description
</th>
</tr>
</thead>
<tbody>
#foreach (var task in Model.Tasks.OrderBy(n => n.TaskDate))
{
<tr>
<td>
#Html.HiddenFor(item => task.TaskID)
#Html.CheckBoxFor(item => task.Assign)
</td>
<td>
#Html.DisplayFor(item => task.TaskStatus)
</td>
<td>
#task.TaskDate.ToLocalTime().ToString("M/d/yyyy")
</td>
<td>
#Html.DisplayFor(item => task.StudentUsername)
</td>
<td>
#Html.DisplayFor(item => task.Description)
</td>
</tr>
}
</tbody>
</table>
<br />
<div class="row">
<div class="col-md-12 alignRight">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#assignment">
Re-Assign
</button>
</div>
</div>
</div>
<div class="modal fade" id="assignment" tabindex="-1" role="dialog" aria-labelledby="assignmentLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="assignmentLabel">Confirm Re-Assignment of Tasks?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Selected tasks will be re-assigned from #Model.FromUsername to #Model.ToUsername</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<input type="submit" value="Confirm" class="btn btn-primary" />
</div>
</div>
</div>
</div>
</form>
<div exclude-if="#Model.Tasks != null && Model.Tasks.Count() > 0">
<div class="alert alert-info">
There are no tasks to re-assign.
</div>
</div>
Can someone help me understand how to do this correctly?
You will need to provide the indexing to your Collection items to posted back in the model as Model binder would use those to bind back the objects to action. So you should be using For loop and IList<T> as your model in view :
#for(int i=0; i< Model.Tasks.Count(); i++)
{
#Html.HiddenFor(item => Model.Tasks[i].TaskID)
#Html.CheckBoxFor(item => Model.Tasks[i].Assign)
............
............
}
and in your model change it to be IList<T> as you wouldn't have indexer on IEnumerable<T>:
public class ReAssignVM
{
public string ToUsername { get; set; }
public string FromUsername { get; set; }
public IList<ReAssignTaskVM> Tasks { get; set; }
} // End of Class

Unable to pass RadioButton group selected value to Controller

I have a ViewModel defined as:
public class Fixtures
{
public int Id { get; set; }
public string HomeTeam { get; set; }
public string AwayTeam { get; set; }
public string HomeTeamCode { get; set; }
public string AwayTeamCode { get; set; }
public string League { get; set; }
public bool Home { get; set; }
public bool Draw { get; set; }
public bool Away { get; set; }
public string FixturePrediction { get; set; }
}
My view displays a list of these fixtures and for each fixture, I have a radio button grouping. I need some way of passing the selected radio button for each fixture to my Post method. My View and controller are as below:
View:
<div class="container">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
for (int i = 0; i < Model.Count(); i++)
{
#Html.HiddenFor(model => model[i].Id)
<div class="col-sm-6">
<div class="panel panel-primary panel-fixture">
<div class="panel-heading text-center fixturetitle">
#Html.DisplayFor(model => model[i].HomeTeam) v #Html.DisplayFor(model => model[i].AwayTeam)
#Html.HiddenFor(model => model[i].HomeTeam)
#Html.HiddenFor(model => model[i].AwayTeam)
</div>
<div class="panel-body">
<div class="container-fluid">
<div class="row">
<div class="col-xs-4 text-center">
<img src="~/Content/Images/#string.Concat(Model[i].HomeTeamCode, ".png")" class="fixturecrest" />
<div class="text-center">
#Html.DisplayFor(model => model[i].HomeTeamCode)
#Html.HiddenFor(model => model[i].HomeTeamCode)
</div>
</div>
<div class="col-xs-4 text-center">
<label class="text-center">
V <br />
</label>
</div>
<div class="col-xs-4 text-center">
<img src="~/Content/Images/#string.Concat(Model[i].AwayTeamCode, ".png")" class="fixturecrest" />
<div class="text-center">
#Html.DisplayFor(model => model[i].AwayTeamCode)
#Html.HiddenFor(model => model[i].AwayTeamCode)
</div>
</div>
</div>
<hr />
<div class="row">
<div class="text-center" role="group" aria-label="Fixture Prediction">
<div class="col-xs-4 text-center">
<button type="button" class="btn btn-xs btn-default">
HOME
#Html.RadioButtonFor(model => model[i].FixturePrediction, Model[i].Home, new { #Name = Model[i].Id })
#Html.HiddenFor(model => model[i].FixturePrediction)
<span class="glyphicon glyphicon-check"></span>
</button>
</div>
<div class="col-xs-4 text-center">
<button type="button" class="btn btn-xs btn-default">
DRAW
#Html.RadioButtonFor(model => model[i].FixturePrediction, Model[i].Draw, new { #Name = Model[i].Id })
#Html.HiddenFor(model => model[i].FixturePrediction)
<span class="glyphicon glyphicon-check"></span>
</button>
</div>
<div class="col-xs-4 text-center">
<button type="button" class="btn btn-xs btn-default">
AWAY
#Html.RadioButtonFor(model => model[i].FixturePrediction, Model[i].Away, new { #Name = Model[i].Id })
#Html.HiddenFor(model => model[i].FixturePrediction)
<span class="glyphicon glyphicon-check"></span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
<input type="submit" value="Confirm Predictions" class="btn btn-success" />
}
</div>
Post Method in Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Test(IEnumerable<Fixtures> test)
{
if (ModelState.IsValid)
{
}
return RedirectToAction("Test");
}
My field FixturePrediction is always null and I have attempted several variations of the 'radiobuttonfor' shown above.
All I need is to assign a value to FixturePrediction based on which radiobutton is selected. What am I missing?
Thanks in advance.
I think what you are trying to do is this, I am not sure why you are doing it the way you are doing it, but this is how you would implement Html.RadioButtonFor, it takes the model prop, and the value, you can add as many buttons as you want, and the selected radio value will be passed as the value for your model prop
#Html.RadioButtonFor(model => model[i].FixturePrediction, "Home")
#Html.RadioButtonFor(model => model[i].FixturePrediction, "Draw")
#Html.RadioButtonFor(model => model[i].FixturePrediction, "Away")
Another example

Partial View with self updating

I'm learning ASP.NET MVC and I've encountered a problem in my practice project (MVC Music Store). I have made a partial view to search for an artist. I expect the partial view to take no arguments and work on its own.
Partial view in the right half part
I have a view specific model for the Artist Search Partial View. The model is as follows:
public class ArtistSearch
{
public string SearchString { get; set; }
public List<Artist> SearchResult { get; set; }
public ArtistSearch()
{
SearchResult=new List<Artist>();
}
}
Controller code is as follows:
public ActionResult Search(string query)
{
ArtistSearch asResult = new ArtistSearch();
if (query != null)
{
var temp = from a in db.Artists
where a.Name.Contains(query)
select a;
asResult.SearchResult = temp.ToList();
asResult.SearchString = query;
}
return PartialView(asResult);
}
The Partial View is as follows:
#model MvcMusicStore.Models.ArtistSearch
<div class="big-search-box">
<form action="#Url.Action("Search","Artist")" method="post" role="form">
<div class="input-group">
#Html.TextBox("query", #Model.SearchString, new { #class = "form-control nrb input-lg", placeholder = "Input your search query..." })
<div class="input-group-btn">
<input type="submit" name="Send" value="Search" class="btn btn-primary btn-iconed btn-lg" />
</div>
</div>
</form>
</div>
<div class="big-search-result-info clearfix">
<div class="pull-left">Showing results for <strong>#Model.SearchString</strong>.</div>
<div class="pull-right"><strong>#Model.SearchResult.Count</strong> artist(s) found.</div>
</div>
<table>
#foreach (var item in #Model.SearchResult)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a href="#item.Id" >
<img src=#item.PhotoURL alt=#item.Name style="width:100px;height:70px;">
</a>
</td>
</tr>
}
</table>
I wish to place this partial view anywhere on the site. Lets say i placed it(using RenderAction) on Artist/Index Controllers View page.
The simple functionality that I'm trying to achieve is that when i click on search it should self update the partial view with search results. Right now it is transferring me to Artist/Search page.
Thanks for the patience.
Try to use Ajax.BeginForm, below is an example:
Action
public ActionResult Search(string query)
{
ArtistSearch asResult = new ArtistSearch();
if (query != null)
{
var temp = from a in db.Artists
where a.Name.Contains(query)
select a;
asResult.SearchResult = temp.ToList();
asResult.SearchString = query;
}
return PartialView("MyParitalView",asResult);
}
View
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("Search", "Home", new AjaxOptions { UpdateTargetId = "result" }))
{
<div class="input-group">
#Html.TextBox("query", #Model.SearchString, new { #class = "form-control nrb input-lg", placeholder = "Input your search query..." })
<div class="input-group-btn">
<input type="submit" name="Send" value="Search" class="btn btn-primary btn-iconed btn-lg" />
</div>
</div>
}
<div id="result"></div>
Parital View : MyParitalView
#model MvcMusicStore.Models.ArtistSearch
<div class="big-search-result-info clearfix">
<div class="pull-left">Showing results for <strong>#Model.SearchString</strong>.</div>
<div class="pull-right"><strong>#Model.SearchResult.Count</strong> artist(s) found.</div>
</div>
<table>
#foreach (var item in #Model.SearchResult)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a href="#item.Id">
<img src=#item.PhotoURL alt=#item.Name style="width:100px;height:70px;">
</a>
</td>
</tr>
}
</table>

Resources