I can't get left join result to view with pagination - linq

i can't pass the result to view, my Index view has pagination.
Index View:
#model rInventarioTI.Clases.PaginationList<rInventarioTI.Models.Productos>
#{
ViewData["Title"] = "Lista Productos";
}
<h1 class="text-center">Listado Productos</h1>
<br />
<br />
<br />
<form asp-action="Index" method="get">
<div class="form-group d-flex justify-content-center">
<p>
Tipo/Serie/Marca/Modelo
<input type="text" name="searchString" value="#ViewData["FiltroActual"]" />
<input type="submit" value="Filtrar" class="btn btn-primary" />
<a asp-action="Index">Borrar filtro</a>
</p>
</div>
</form>
<p class="float-end">
<a asp-action="Create" class="btn btn-success">Crear nuevo</a>
</p>
<table class="table">
<thead class="bg-dark" style="color: white;">
<tr>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["TypeProductNameSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">Tipo de producto <i class="fas fa-sort-amount-down-alt"></i> </a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["COGSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">COG <i class="fas fa-sort-amount-down-alt"></i></a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["SerieSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">Numero de Serie <i class="fas fa-sort-amount-down-alt"></i></a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["MarcaSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">Marca <i class="fas fa-sort-amount-down-alt"></i></a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["ModeloSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">Modelo Equipo<i class="fas fa-sort-amount-down-alt"></i></a>
</th>
<th>
#*#Html.DisplayNameFor(model => model.TiposMovimientosNav)*#
Movimiento
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="#ViewData["DateSortParm"]"
asp-route-filtroActual="#ViewData["FiltroActual"]">Fecha Registro<i class="fas fa-sort-amount-down-alt"></i></a>
</th>
<th>Operaciones</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.TiposProductosNav.Nombre)
</td>
<td>
#Html.DisplayFor(modelItem => item.COG)
</td>
<td>
#Html.DisplayFor(modelItem => item.NumeroSerie)
</td>
<td>
#Html.DisplayFor(modelItem => item.MarcasNav.Nombre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Modelo)
</td>
<td>
#Html.DisplayFor(modelItem => item.MovimientosProductosNav)
</td>
<td>
#Html.DisplayFor(modelItem => item.FechaAlta)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id"><i class="fas fa-pencil-alt"></i></a> |
<a asp-action="Details" asp-route-id="#item.Id"><i class="fas fa-eye"></i></a> |
<a asp-action="Delete" asp-route-id="#item.Id"><i class="fas fa-trash-alt"></i></a> |
<a asp-action="Asignar" asp-route-id="#item.Id"><i class="fas fa-arrow-right"> Asignar</i></a> |
<a asp-action="Desasignar" asp-route-id="#item.Id"><i class="fas fa-arrow-left"> Desasignar</i></a> |
<a asp-action="Transferir" asp-route-id="#item.Id"><i class="fas fa-exchange-alt"> Transferir</i></a>
</td>
</tr>
}
</tbody>
</table>
#{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}
<a asp-action="Index"
asp-route-sortOrder="#ViewData["OrdenamientoActual"]"
asp-route-pageNumber="#(Model.PageIndex + 1)"
asp-route-filtroActual="#ViewData["FiltroActual"]"
class="btn btn-primary #nextDisabled float-end">Adelante</a>
<a asp-action="Index"
asp-route-sortOrder="#ViewData["OrdenamientoActual"]"
asp-route-pageNumber="#(Model.PageIndex - 1)"
asp-route-filtroActual="#ViewData["FiltroActual"]"
class="btn btn-primary #prevDisabled float-end">Atrás</a>
PaginationList
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace rInventarioTI.Clases
{
public class PaginationList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public PaginationList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
public static async Task<PaginationList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
return new PaginationList<T>(items, count, pageIndex, pageSize);
}
}
}
Productos Model:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace rInventarioTI.Models
{
//[Index(nameof(COG), IsUnique = true)]
public partial class Productos
{
public Productos()
{
MovimientosProductosNav = new HashSet<MovimientosProductos>();
}
public int Id { get; set; }
[Display(Name = "Tipo de producto")]
//[Required(ErrorMessage = "Seleccione un tipo de producto")]
public int TiposProductosID { get; set; }
[Display(Name = "Marca")]
public int MarcasID { get; set; }
// Algunos productos pueden no tener numero de serie.
[Display(Name = "Numero Serie")]
public string NumeroSerie { get; set; }
[Display(Name = "Descripcion")]
[Required(ErrorMessage = "Ingrese una descripción")]
[StringLength(1500, MinimumLength = 6, ErrorMessage = " Caracteres permitidos, mas de 6 y menos de 1500")]
public string Descripcion { get; set; }
[Display(Name = "Modelo del producto")]
[Required(ErrorMessage = "Ingrese un modelo para este producto")]
public string Modelo { get; set; }
[Display(Name = "Color de producto")]
[Required(ErrorMessage = "Ingrese un color para este producto")]
public string Color { get; set; }
[Display(Name = "Codigo del fabricante")]
public string CodigoFabricante { get; set; }
// Clave unica e irrepetible. TODOS los productos deben tener
// un COD definido y asignado por el sistema.
[Display(Name = "COG")]
[Required(ErrorMessage = "Ingrese un COG")]
[StringLength(25, MinimumLength = 3, ErrorMessage = "Ingrese un COG de entre 3 y 25 caracteres")]
public string COG { get; set; }
[Display(Name = "Datos QR del producto")]
public string CodigoQr { get; set; }
[Display(Name = "Fecha de Registro")]
public DateTime FechaAlta { get; set; }
[Display(Name = "Tipo de producto")]
public virtual TiposProductos TiposProductosNav { get; set; }
[Display(Name = "Marcas")]
public virtual Marcas MarcasNav { get; set; }
public virtual ICollection<MovimientosProductos> MovimientosProductosNav { get; set; }
}
}
MovimientosProductos Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace rInventarioTI.Models
{
public partial class MovimientosProductos
{
public MovimientosProductos() {
}
public int id { get; set; }
[Required]
public int ProductosID { get; set; }
[Display(Name = "Tipo Movimiento")]
[Required]
public int TiposMovimientosID { get; set; }
[Display(Name = "Usuario Genera Movimiento")]
public int UsuariosID { get; set; }
[Display(Name = "Oficina Destino")]
public int OficinasID { get; set; }
[Display(Name = "Estado físico del producto")]
public int EstadosProductosID { get; set; }
[Display(Name = "Observaciones del movimiento y/o producto")]
[Required(ErrorMessage = "Observaciones del movimiento y/o producto")]
[StringLength(1500, MinimumLength = 6, ErrorMessage = "Minimo 6 caracteres, maximo 1500 caracteres.")]
public string Observaciones { get; set; }
[Display(Name = "Fotos del producto")]
public string PathFotos { get; set; }
[Display(Name = "Fecha de Registro")]
public DateTime FechaAlta { get; set; }
[Display(Name = "Produco")]
public virtual Productos ProductosNav { get; set; }
[Display(Name = "Tipo Movimiento")]
public virtual TiposMovimientos TiposMovimientosNav { get; set; }
[Display(Name = "Usuario generó movimiento")]
public virtual Usuarios UsuariosNav { get; set; }
[Display(Name = "Oficina asignada")]
public virtual Oficinas OficinaNav { get; set; }
[Display(Name = "Estado del producto")]
public virtual EstadosProductos EstadosProductosNav { get; set; }
}
}
Productos Controller
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 rInventarioTI.Models;
using rInventarioTI.Clases;
using System.Collections.Generic;
//using System.Data.Entity;
namespace rInventarioTI.Controllers
{
public class ProductosController : Controller
{
private readonly rInventarioContext _context;
public ProductosController(rInventarioContext context)
{
_context = context;
}
// GET: Productos
public async Task<IActionResult> Index(
string sortOrder,
string filtroActual,
string searchString,
int? pageNumber)
{
ViewData["OrdenamientoActual"] = sortOrder;
ViewData["TypeProductNameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "Name_desc" : "";
ViewData["COGSortParm"] = sortOrder == "COG" ? "COG_desc" : "COG";
ViewData["SerieSortParm"] = sortOrder == "Serie" ? "Serie_desc" : "Serie";
ViewData["MarcaSortParm"] = sortOrder == "Marca" ? "Marca_desc" : "Marca";
ViewData["ModeloSortParm"] = sortOrder == "Modelo" ? "Modelo_desc" : "Modelo";
ViewData["DatesortParm"] = sortOrder == "Date" ? "Date_desc" : "Date";
// Valido si hay cadena de búsqueda ingresada
if (searchString != null)
{
pageNumber = 1;
} else
{
searchString = filtroActual;
}
ViewData["FiltroActual"] = searchString;
//var productos = (from prod in _context.Productos
// select prod)
// .Include(m => m.MarcasNav).AsQueryable()
// .Include(t => t.TiposProductosNav).AsQueryable()
// .Include(ep => ep.MovimientosProductosNav).AsQueryable();
/*
Recupera listado de productos, donde el numero de movimientos sea de 2 o mas.
*/
var productos = (from prod in _context.Productos.ToList()
join mov in _context.MovimientosProductos on prod.Id equals mov.ProductosID into ProductosMovimientosGroup
from mov in ProductosMovimientosGroup.DefaultIfEmpty()
where (ProductosMovimientosGroup.Count() == 0)
select prod);
if (!String.IsNullOrEmpty(searchString))
{
productos = productos.Where(
prod => prod.TiposProductosNav.Nombre.Contains(searchString) ||
//prod.SerialesProductosID.
prod.MarcasNav.Nombre.Contains(searchString) ||
prod.Modelo.Contains(searchString) ||
prod.COG.Contains(searchString));
}
switch (sortOrder)
{
case "Name_desc":
productos = productos.OrderByDescending(prod => prod.TiposProductosNav.Nombre);
break;
case "COG":
productos = productos.OrderBy(prod => prod.COG);
break;
case "COG_desc":
productos = productos.OrderByDescending(prod => prod.COG);
break;
case "Serie":
productos = productos.OrderBy(prod => prod.NumeroSerie);
break;
case "Serie_desc":
productos = productos.OrderByDescending(prod => prod.NumeroSerie);
break;
case "Marca":
productos = productos.OrderBy(prod => prod.MarcasNav.Nombre);
break;
case "Marca_desc":
productos = productos.OrderByDescending(prod => prod.MarcasNav.Nombre);
break;
case "Modelo":
productos = productos.OrderByDescending(prod => prod.Modelo);
break;
case "Modelo_desc":
productos = productos.OrderBy(prod => prod.Modelo);
break;
case "Date":
productos = productos.OrderBy(prod => prod.FechaAlta);
break;
case "Date_desc":
productos = productos.OrderByDescending(prod => prod.FechaAlta);
break;
default:
productos = productos.OrderBy(prod => prod.TiposProductosNav.Nombre);
break;
}
int pageSize = 10;
return View(await PaginationList<Productos>.CreateAsync(
productos.AsNoTracking(),
pageNumber ?? 1,
pageSize));
//return View(productos);
}
}
}
Source: Tutorial: Add sorting, filtering, and paging - ASP.NET MVC with EF Core
My query in SQL works fine
Image SQL Script works
SELECT Productos.COG, Productos.Id
from Productos
left join MovimientosProductos on MovimientosProductos.ProductosID = Productos.Id
Group by Productos.Id, Productos.COG
having COUNT(MovimientosProductos.ProductosID) = 0
SELECT Productos.COG, Productos.Id, ProductosID
from MovimientosProductos
RIGHT join Productos on Productos.Id = MovimientosProductos.ProductosID
Group by Productos.COG, Productos.Id, ProductosID
having ProductosID IS NULL
My query in Linq is:
var productos = (from prod in _context.Productos.ToList()
join mov in _context.MovimientosProductos on prod.Id equals mov.ProductosID into ProductosMovimientosGroup
from mov in ProductosMovimientosGroup.DefaultIfEmpty()
where ProductosMovimientosGroup.Count() == 0
select prod);
and in debug mode productos has 3 records. Works fine.
But when the app runs, i get this error:
Severity Code Description Project File Line Suppression State
Error CS1061 'IEnumerable' does not contain a definition
for 'AsNoTracking' and no accessible extension method 'AsNoTracking'
accepting a first argument of type 'IEnumerable' could be
found (are you missing a using directive or an assembly reference?)
I understand that i need to get IQueryable result instead of IEnumerable, but how can i convert the result?
Then, i have removed ToList() from the query and AsNoTracking() from the return View for test, but now the error is:
An unhandled exception occurred while processing the request.
InvalidOperationException: The LINQ expression 'DbSet()
.LeftJoin( inner: DbSet(), outerKeySelector: p
=> p.Id, innerKeySelector: m => m.ProductosID, resultSelector: (p, m) => new TransparentIdentifier<Productos, MovimientosProductos>( Outer = p, Inner = m )) .Where(ti => ProductosMovimientosGroup .Count() == 0)'
could not be translated. Either rewrite the query in a form that can
be translated, or switch to client evaluation explicitly by inserting
a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or
'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for
more information.
But i don't know how to translate the query...
Thank you

Thank you all for your comments
Gert Arnold mentioned the navigation properties and then changed the query for this:
var productos = (from p in _context.Productos
.Include(mp => mp.MovimientosProductosNav)
.Include(m => m.MarcasNav)
.Include(tp => tp.TiposProductosNav).ToList()
select p);
I get the properties by "navigation properties" declared in my models and the view get model without any problem.
Now it works.

Related

Unable to remove mandatory validation in MVC

I am not an expert MVC programmer but have to make a small change in the code. Any help?
I have a field CallerType which had [required] attribute. However, I do not want to be mandatory anymore so I am removing [required] attribute but still get the same input required error.
public virtual CallType CallType { get; set; }
[Display(Name = "Type of Calls")]
/*Akbar-start*[Required]*Akbar-end*/
public int CallTypeID { get; set; }
<div class="form-group col-3">
<label asp-for="Intake.CallTypeID" class="control-label"></label>
<select asp-for="Intake.CallTypeID"class="form-control">asp-items="Model.CallTypes">
<option value="">Please Select</option>
</select>
<span asp-validation-for="Intake.CallTypeID" class="text-danger"></span>
</div>
Error:
enter image description here
I also see javascript like below but not sure how this is getting invoked:
$('input').each(function () {
var req = $(this).attr('data-val-required');
var hide = $(this).attr('hide-required-indicator');
var hasIndicator = $(this).hasClass('has-required-indicator');
if (undefined != req && undefined == hide && !hasIndicator) {
var label = $('label[for="' + $(this).attr('id') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red" class="required-indicator"> *</span>');
$(this).addClass('has-required-indicator');
}
}
});
$('select').each(function () {
var req = $(this).attr('data-val-required');
var hasIndicator = $(this).hasClass('has-required-indicator');
if (undefined != req && !hasIndicator) {
var label = $('label[for="' + $(this).attr('id') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red"> *</span>');
$(this).addClass('has-required-indicator');
}
}
});
I was able to solve this issue.
Here is the trick:
Changed int to int?
public int CallTypeID { get; set; }
i.e.
public int? CallTypeID { get; set; }
? indicates that this field is nullable. It was overriding [Required] attribute

Set enum values as selected in Razor dropdown

I am using a razor view for showing the scored of an examination and it contains an enum value that holds 3 values "pass","Fail","absent" and i want to choose it accordingly. The model i used is
model
public class VerifyResultModel
{
[Display(Name = "StudnetId")]
public int StudentId { get; set; }
[Display(Name = "Student")]
[Required]
public string Student { get; set; }
[Display(Name = "Mark")]
[Required]
public int Mark { get; set; }
[Display(Name = "Score")]
[Required]
public string Score { get; set; }
[Display(Name = "Result")]
public App.EnumValues.ExamResultStatus Result { get; set; }
}
Controller
[HttpGet]
public ActionResult Verify(int Id)
{
List<VerifyResultModel> model_result = new List<VerifyResultModel>();
VerifyResultModel _resultItem;
foreach (exammark item in marks)
{
SchoolApp.EnumValues.ExamResultStatus result = SchoolApp.EnumValues.ExamResultStatus.Absent;
if(item.Mark >= MinMark)
{
result= SchoolApp.EnumValues.ExamResultStatus.Pass;
}
else
{
result = App.EnumValues.ExamResultStatus.Fail;
}
_resultItem = new VerifyResultModel { StudentId = (int)item.StudentId, Student = item.studentmaster.StudentName, Mark = (int)item.Mark, Score = item.Mark.ToString(), Result = result };
model_result.Add(_resultItem);
}
LoadResultsDropdown();
return View(model_result);
}
private void LoadResultsDropdown()
{
var types = (from App.EnumValues.ExamResultStatus type in Enum.GetValues(typeof(SchoolApp.EnumValues.ExamResultStatus))
select new { Id = type.ToString(), Name = type.ToString() }).ToList();
ViewBag.ResultList = new SelectList(types, "Id", "Name");
}
View
#model IList<SchoolApp.ViewModels.VerifyResultModel>
<tbody>
#for (int item = 0; item < Model.Count(); item++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model[item].Student)
</td>
<td>
#Html.DisplayFor(modelItem => Model[item].Mark)
</td>*#
<td>
#Html.DisplayFor(modelItem => Model[item].Score)
</td>
<td>
#Html.DropDownListFor(model => model[item].Result, (SelectList)ViewBag.ResultList) //Here All values are showing as Pass ( first item in dropdown)
</td>
</tr>
}
</tbody>
The problem is even if i pass values Fail / Absent to enum it shows as Pass in combobox . How can i show the correct value ?
Can you please try this:
private void LoadResultsDropdown()
{
var types = (from App.EnumValues.ExamResultStatus type in Enum.GetValues(typeof(SchoolApp.EnumValues.ExamResultStatus))
select new { Id = type.ToString(), Name = type.ToString() }).ToList();
var types=Enum.GetValues(typeof(ExamResultStatus)).Cast<ExamResultStatus>();
var EnumData= types.Select(c => new { c.Key, c.Value });
ViewBag.ResultList = new SelectList(types.AsEnumerable(), "key", "value");
}
Hope this helps..

Does not contain a definition for 'IdCriterion'

I have a ViewModel in: RolesMVC3.Area.Asesor.Models.ListNotesViewModel
is the following:
public class ListNotesViewModel
{
public decimal IdTime { get; set; }
public decimal IdArea { get; set; }
public decimal IdCriterion { get; set; }
public decimal Notes { get; set; }
public decimal IdEstudent { get; set; }
}
I have a controller that uses this ViewModel.
is the following:
public ActionResult EstudentsQualification()
{
var newItems = (from n in db.Qualification
join a in db.AREA on n.IdArea equals a.IdArea
join e in db.ESTUDENT on n.IdEstudent equals e.IdEstudent
join p in db.TIME on n.IdTime equals p.IdTime
join c in db.CRITERION on n.IdCriterion equals c.IdCriterion
where n.IdArea == 1
select new ListNotesViewModel { IdCriterion = c.IdCriterion, IdTime = p.IdTime, Notes=n.Note, IdEstudent==e.IdEstudent }).ToList();
var estu = (from n in db.Qualification
join e in db.ESTUDENT on n.IdEstudent equals e.IdEstudent
where n.IdArea == 1
select e).Distinct().ToList();
ViewBag.Estudents = estu;
ViewBag.Time = db.TIME;
ViewBag.Criterion = db.CRITERION;
ViewBag.Notes = newItems;
return View();
}
the associated view is:
#{
ViewBag.Title = "Index";
}
<table border="1">
#foreach (var item4 in ViewBag.Estudents)
{
<tr>
<td>
#item4.CodEstudents - #item4.NameEstudents
</td>
#foreach (var item2 in ViewBag.Time)
{
foreach (var item3 in ViewBag.Criterion)
{
<td>
#if (ViewBag.Notes.IdCriterion == item3.IdCriterion && ViewBag.Notes.IdTime == item2.IdTime && ViewBag.Notes.IdEstudent == item4.IdEstudent)
{
#ViewBag.Notes.Note
}
else
{
#:nothing
}
</td>
}
}
</tr>
}
</table>
I get the following error:
'System.Collections.Generic.List<RolesMVC3.Area.Asesor.Models.ListNotesViewModel>' does not contain a definition for 'IdCriterion'
I can't figure out what the problem is.
Think this line caused it ViewBag.Notes.IdCriterion
#if (ViewBag.Notes.IdCriterion == item3.IdCriterion && ViewBag.Notes.IdTime == item2.IdTime && ViewBag.Notes.IdEstudent == item4.IdEstudent)
ViewBag.Notes is a collection of Note. You need to access item in Notes e.g. ViewBag.Notes[0].IdCriterion or ViewBag.Notes[i].IdCriterion or foreach(noteItem in ViewBag.Notes)

how to delete previusly selected file based on index value in mvc3?

Hi all i am working on mvc3
here i need to delete a previously uploaded file from the sessions data
anh i am displaying the file before inserting into data base so i am displaying the data in sessions now i need to delete the previously selected file plz help to how to get the selected file index value to delete the file from the sessions
For example here check this post it is in c# but i need this is in mvc3 please help me to do this work plz help me anyone
here my models are
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace BugTracker.Models
{
public class BugModel
{
public BugModel()
{
if (ListFile == null)
ListFile = new List<BugAttachment>();
}
public List<BugAttachment> ListFile { get; set; }
public string ErrorMessage { get; set; }
}
public class BugAttachment
{
public string FileName { get; set; }
public int BugAttachmentID { get; set; }
public string AttachmentName { get; set; }
public int BugID { get; set; }
public string AttachmentUrl { get; set; }
public string AttachedBy { get; set; }
}
}
here my controllers
public ActionResult UploadFile(string AttachmentName, BugModel model)
BugModel bug = null;
if (Session["CaptureData"] == null)
{
bug = model;
}
else
{
bug = (BugModel)Session["CaptureData"];
}
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file1 = Request.Files[inputTagName];
if (file1.ContentLength > 0)
{
BugAttachment attachment = new BugAttachment();
var allowedExtensions = new[] { ".doc", ".xlsx", ".txt", ".jpeg", ".docx" };
var extension = Path.GetExtension(file1.FileName);
if (!allowedExtensions.Contains(extension))
{
model.ErrorMessage = "{ .doc, .xlsx, .txt, .jpeg }, files are allowed.... ";
}
else
{
string filename = Guid.NewGuid() + Path.GetFileName(file1.FileName);
string path = "/Content/UploadedFiles/" + filename;
string savedFileName = Path.Combine(Server.MapPath("~" + path));
file1.SaveAs(savedFileName);
attachment.FileName = "~" + path.ToString();
attachment.AttachmentName = AttachmentName;
attachment.AttachmentUrl = attachment.FileName;
bug.ListFile.Add(attachment);
model = bug;
}
Session["CaptureData"] = model;
}
}
ModelState.Clear();
return View("LoadBug", bug);
}
and here my view page
<div class="UploadMain">
<%:Html.Label("Attachment Name:") %>
<%:Html.TextBoxFor(model=>model.AttachmentName) %>
<span>
<%:Html.Label("Upload Files") %></span>
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" id="Upload" class="style-name cancel" />
<%--onclick="window.location.href='<%= Url.Action("UploadFile", "Bug") %>';"--%>
<table align="center" class="gridtable" border="0" cellspacing="0" cellpadding="0">
<tr>
<th>
Attachment Name
</th>
<th>
Attachment Url
</th>
<th>
Action
</th>
</tr>
<% if (Model != null && Model.ListFile != null)
{ %>
<% foreach (var Emp in Model.ListFile)
{ %>
<tr class="Data">
<td >
<%:Emp.AttachmentName %>
</td>
<td >
<%: Emp.FileName %>
</td>
<td>
<%-- <%= Html.ActionLink("Delete", "Delete")%>--%>
<%:Html.ActionLink("Delete", "Delete", new { #FileName = Emp.FileName })%>
</td>
</tr>
<% } %>
<% } %>
</table>
</div>
For example here check this post it is in c# but i need this is in mvc3 please help me to do this work plz help me anyone
thanks in advance
To delete a file you uploaded all you need is its filepath, and use File.Delete("filepath");
To know which file to delete your Delete action should take an id:
Delete(int id)
Then in your action link pass the BugAttachmentID: (using route values/parameters)
<%:Html.ActionLink("Delete", "Delete", new { #FileName = Emp.FileName }, new { id = Emp.BugAttachmentID })%>
Then in your delete method you use the ID to find the file in the FileList you want to delete. And then call File.Delete using the attachment url.
I hope this helps.

MVC3 partial view with ViewModel property as model

I'm trying to pass a ViewModel property to a partial view, but getting the following error:
"The model item passed into the dictionary is of type '<>f__AnonymousType2`1[DomaniOnline.Models.DomaniData.TempRates]', but this dictionary requires a model item of type 'DomaniOnline.Models.DomaniData.TempRates'."
How do I pass the VM property so that it is not an anonymous type?
The View:
#model DomaniOnline.Models.ViewModels.CompareRatesViewModel
#{
ViewBag.Title = "Rate Comparison";
}
<h2>Compare Rates</h2>
<table>
<tr>
<td>#Html.DisplayTextFor(m=>m.TempRate1.CarrierName)</td>
<td>#Html.DisplayTextFor(m=>m.TempRate2.CarrierName)</td>
<td>#Html.DisplayTextFor(m=>m.TempRate3.CarrierName)</td>
<td>#Html.DisplayTextFor(m=>m.TempRate4.CarrierName)</td>
</tr>
<tr>
<td>#Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate1 })</td>
<td>#Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate2 })</td>
<td>#Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate3 })</td>
<td>#Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate4 })</td>
</tr>
</table>
The Partial View:
#model DomaniOnline.Models.DomaniData.TempRates
<fieldset>
<legend>TempRates</legend>
<div class="display-label">Carrier Name</div>
<div class="display-field">
#Html.DisplayFor(model => model.CarrierName)
</div>
....
</fieldset>
And the ViewModel:
public class CompareRatesViewModel
{
public TempRates TempRate1 { get; set; }
public TempRates TempRate2 { get; set; }
public TempRates TempRate3 { get; set; }
public TempRates TempRate4 { get; set; }
public TempRates TempRate5 { get; set; }
public CompareRatesViewModel(IEnumerable<TempRates> TempRateList)
{
this.TempRate1 = TempRateList[0];
this.TempRate2 = TempRateList[1];
this.TempRate3 = TempRateList[2];
this.TempRate4 = TempRateList[3];
this.TempRate5 = TempRateList[4];
}
}
Why not just pass in the object directly rather than using an anonymous type?
Your partial takes TempRates and your TempRate1 is of type TempRate so you should be able to do this without casting.
<td>#Html.Partial("_TempRatesPartial", Model.TempRate1)</td>
You need to cast your anonymous type as the type that is the model of your partial view:
#Html.Partial("_TempRatesPartial", (DomaniOnline.Models.DomaniData.TempRates)Model.TempRate1)

Resources