I have to display my details in the list view .I am storing my details in controller using viewdata and i need to use the viewdata in my view .The view part is not working.IN view part i have to use view data inside foreach and iterate through the list .Help me out!!
Previously i was storing in static list given below:
public static List<EmployeeModel> staticEmployeeViewModelList = new List<EmployeeModel>();
my controller part
public async Task<IActionResult> ImportEmployeeDetails(IFormFile excelfile)
{
try
{
EmployeesViewModelList employeesListObject = new EmployeesViewModelList();
// var employeesListObject = new EmployeesViewModelList();
List<EmployeeModel> employeesViewModelList = new List<EmployeeModel>();
if (excelfile == null || excelfile.Length == 0)
{
return View(employeesListObject);
}
var supportedTypes = new[] { ".xls", ".xlsx" };
var ext = Path.GetExtension(excelfile.FileName);
if (!supportedTypes.Contains(ext))
{
return View(employeesListObject);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot",
"EmployeeDetails.xlsx");
FileInfo file = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
for (int i = 2; i <= rowCount; i++)
{
EmployeeModel emp = new EmployeeModel();
// emp.EmployeeId = Convert.ToInt32(worksheet.Cells[i, 1].Value.ToString());
emp.EmpEin = worksheet.Cells[i, 1].Value.ToString();
emp.EmpFirstName = worksheet.Cells[i, 2].Value.ToString();
employeesViewModelList.Add(emp);
}
ViewData["EmployeeList"] = employeesViewModelList;
//to get data
employeesViewModelList = ViewData["EmployeeList"] as List<EmployeeModel>;//convert back to llist
staticEmployeeViewModelList = employeesViewModelList.ToList();
ViewData["EmployeeList"] = employeesViewModelList.ToList();
employeesListObject.EmpModelList = employeesViewModelList;
employeesViewModelList = ViewData["EmployeeList"] as List<EmployeeModel>;
// return View(employeesListObject);
return View(employeesListObject);
}
}
catch(Exception ex)
{
ViewData["Message"] = "Opps! Something Went wrong!";
return RedirectToAction("ExcelPackage");
}
}
My View:
My view
// In foreach loop i have used the below code
#foreach (var employee in (List)TempData["EmployeeList"])
{
#foreach(var item in employee.EmpModelList.ToList())
{
// the above one is not working
--------------------------------------------------------------------------
Save
EmpEin
FirstName
LastName
Email
Country
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.EmpModelList.ToList())
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.EmpEin)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmpFirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmpLastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmpEmail)
</td>
<td>
#Html.DisplayFor(modelItem => item.HomeCountry)
</td>
<td>
<td><a class="edit" href="javascript:;">Edit</a></td>
<td class="EmpId" style="display:none">#Html.DisplayFor(modelItem => item.EmpEin)</td>
</td>
</tr>
}
</tbody>
</table>
</div>
}
In order to use ViewData in view ,first we have to store the list of properties in controller using an object .As we need to bind the model class in the view to get the list properties and we have to use the model directly in view .
#using ECOLAB.SIP.Web.XXXXXX #*(model folder)*#
#model ECOLAB.SIP.Web.Models.XXXXXXX #*(class name inside the model folder)*#
after that we have to implement like below
var emplist = ViewData['List'] #*(name should match with the controller)*#
var list=emplist as employeemodel #*(this is my model class name)*#
foreach(var item in list)
{
<li>#item.EmployeeName</li>
}
Related
I'm facing a problem with a table inside a partial view, where each row have an dropDownListFor for status list and a button "change status".
But my problem is, if i have 3 row's and change the status when the view model get to controller the selected satus is the status of first row and not the status changed on selected row.
Controller:
public ActionResult AlterarEstadoAfericao(GestaoAfericoesViewModel model)
{
GestaoAfericoesDbo gestaoAfericoesDbo = new GestaoAfericoesDbo();
DbUtil dbUtil = new DbUtil();
string connectionString = dbUtil.generateConnectionString(Connections.Endpoint);
IntranetDbContext db;
db = new IntranetDbContext(connectionString);
var idEstado = db.AF_Estado.Where(a => a.descricao.Equals(model.SelectedEstadoRow)).ToList().First();
int id_estado = Convert.ToInt32(idEstado.id);
try
{
var dbAF_afericao = db.AF_afericao.Find(model.idSelected);
dbAF_afericao.id_estado_actual = Convert.ToInt32(id_estado);
db.SaveChanges();
}
catch(SqlException exc)
{
Console.WriteLine(exc);
}
return RedirectToAction("/GestaoAfericoes");
}
Partial View:
#using (Html.BeginForm("AlterarEstadoAfericao", "Ferramentas", FormMethod.Post))
{
<table id="table" class="table">
<tr>
<th>Id</th>
<th>Descrição</th>
<th>Início</th>
<th>Fim</th>
<th>Origem</th>
<th>Estado</th>
<th></th>
<th></th>
</tr>
#if (Model.listGestaoAfericoes != null)
{
foreach (var item in Model.listGestaoAfericoes)
{
<tr id="#item.id">
<td id="id">#item.id</td>
<td>#item.descricao</td>
<td>#item.data_ini_afericao</td>
<td>#item.data_fim_afericao</td>
<td id="origem">#item.origem_afericao</td>
<td>#item.id_estado_actual</td>
#Html.HiddenFor(model => model.idSelected, new { #Value = #item.id})
<td>Estado: #Html.DropDownListFor(model => model.SelectedEstadoRow, (IEnumerable<SelectListItem>)Model.listEstados)</td>
<td>
#Html.ActionLink("Alterar Estado", "AlterarEstadoAfericao", null,
new { onclick = "return confirm('Tem a certeza que pretende alterar o estado?');", #class = "btn btn-info" })
</td>
</tr>
}
}
</table>
}
Anyone can help-me to resolve this question?
Greetings
I tried another way to try a resolution to the problem, but no success.
Partial View:
foreach (var item in Model.listGestaoAfericoes)
{
<tr id="#item.id">
<td id="id">#item.id</td>
<td>#item.descricao</td>
<td>#item.data_ini_afericao</td>
<td>#item.data_fim_afericao</td>
<td id="origem">#item.origem_afericao</td>
<td>#item.id_estado_actual</td>
#Html.HiddenFor(model => model.idSelected, new { #Value = #item.id })
<td>Estado: #Html.DropDownListFor(model => item.SelectedEstadoRow, (IEnumerable<SelectListItem>)Model.listEstados)</td>
<td>
#Html.ActionLink("Alterar Estado", "AlterarEstadoAfericao", new { item.id, item.SelectedEstadoRow },
new { onclick = "return confirm('Tem a certeza que pretende alterar o estado?');", #class = "btn btn-info" })
</td>
</tr>
}
Controller:
public ActionResult AlterarEstadoAfericao(Decimal id, string SelectedEstadoRow)
{
GestaoAfericoesDbo gestaoAfericoesDbo = new GestaoAfericoesDbo();
DbUtil dbUtil = new DbUtil();
string connectionString = dbUtil.generateConnectionString(Connections.Endpoint);
IntranetDbContext db;
db = new IntranetDbContext(connectionString);
var idEstado = db.AF_Estado.Where(a => a.descricao.Equals(SelectedEstadoRow)).ToList().First();
int id_estado = Convert.ToInt32(idEstado.id);
try
{
var dbAF_afericao = db.AF_afericao.Find(id);
dbAF_afericao.id_estado_actual = Convert.ToInt32(id_estado);
db.SaveChanges();
}
catch (SqlException exc)
{
Console.WriteLine(exc);
}
return RedirectToAction("/GestaoAfericoes");
}
The id came to controller with correct value, but SelectedEstadoRow have a null value on the controller.
I implemente dynamic add and remove column it's working fine if I remove last row but if I remove first index then it's losing all other rows.
But if I use FormCollection Its binding but not as array list
public ActionResult Index()
{
var employee = new Employee();
employee.Skills.Insert(0, new Skill());
return View(employee);
}
.cshtml
<table id="skills-table">
<thead>
<tr>
<th style="width:20px;"> </th>
<th style="width:160px;">Skill</th>
<th style="width:150px;">Level</th>
<th style="width:32px;"> </th>
</tr>
</thead>
<tbody>
#for (var j = 0; j < Model.Skills.Count; j++)
{
<tr valign="top">
<th><span class="rownumber"></span></th>
<td>
#Html.TextBoxFor(model => model.Skills[j].Title, new { #class = "skill-title" })
#Html.ValidationMessageFor(model => model.Skills[j].Title)
</td>
<td>
#Html.DropDownListFor(
model => model.Skills[j].Level,
new SelectList(WebApplication4.MetaModels.SkillLevel.GetSkillLevels(), "Code", "Description", Model.Skills[j].Level),
"-- Select --",
new {#class = "skill-level"}
)
#Html.ValidationMessageFor(model => model.Skills[j].Level)
</td>
<td>
#if (j < Model.Skills.Count - 1)
{
<button type="button" class="remove-row" title="Delete row"> </button>
}
else
{
<button type="button" class="new-row" title="New row"> </button>
}
</td>
</tr>
}
</tbody>
</table>
jQuery:
<script type="text/javascript">
var addRow = function () {
addTableRow($("#skills-table"));
return false;
};
var deleteRow = function (event) {
$(event.target).closest("tr").remove();
return false;
};
function addTableRow(table) {
/* Sources:
http://www.simonbingham.me.uk/index.cfm/main/post/uuid/adding-a-row-to-a-table-containing-form-fields-using-jquery-18
http://stackoverflow.com/questions/5104288/adding-validation-with-mvc-3-jquery-validator-in-execution-time
*/
var $ttc = $(table).find("tbody tr:last");
var $tr = $ttc.clone();
$tr.find("input,select").attr("name", function () { // find name in the cloned row
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts from id, including index
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new name
}).attr("id", function () { // change id also
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts
return parts[1] + "_" + ++parts[2] + "__" + parts[3]; // build new id
});
$tr.find("span[data-valmsg-for]").attr("data-valmsg-for", function () { // find validation message
var parts = $(this).attr("data-valmsg-for").match(/(\D+)\[(\d+)]\.(\D+)$/); // extract parts from the referring attribute
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new value
})
$ttc.find(".new-row").attr("class", "remove-row").attr("title", "Delete row").unbind("click").click(deleteRow); // change buttin function
$tr.find(".new-row").click(addRow); // add function to the cloned button
// reset fields in the new row
$tr.find("select").val("");
$tr.find("input[type=text]").val("");
// add cloned row as last row
$(table).find("tbody tr:last").after($tr);
// Find the affected form
var $form = $tr.closest("FORM");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// We could re-validate with changes
// $form.validate($form.data("unobtrusiveValidation").options);
};
(function ($) {
/* Source:
http://www.johnculviner.com/post/2011/11/16/ClearReset-MVC-3-Form-and-Unobtrusive-jQuery-Client-Validation.aspx
*/
$.fn.resetValidation = function () {
var $form = this.closest('form');
//reset jQuery Validate's internals
$form.validate().resetForm();
//reset unobtrusive validation summary, if it exists
$form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul").empty();
//reset unobtrusive field level, if it exists
$form.find("[data-valmsg-replace]")
.removeClass("field-validation-error")
.addClass("field-validation-valid")
.empty();
return $form;
};
})(jQuery);
$(function () {
$(".new-row").click(addRow);
$(".remove-row").click(deleteRow);
})
</script>
Controller:
public ActionResult Index(Employee employee, FormCollection abc, string[]dynamic)
{
return View(employee);
}
Here my FormCollection is getting all the data but not as array type
I'm trying to make a table that has searching, sorting, and filtering (any number of available filters). When I sort the filters get overwritten and I'm not sure how to make sure they stay in the querystring since they are stored in the model as an array of strings.
I've tried using the ViewBag and the asp-route-varName tag but it didn't work since it's an array. I thought since they are all in the same form that they should just append to the querystring not overwrite it. The sort and search works since search is just a string. The filter and search works not entirely sure why.
View:
#model ScenarioLake.Api.Host.WebApplication.Models.MasterModel;
<form asp-controller="FileList" asp-action="Index" method="get">
<p>
Title: <input type="text" name="SearchString" />
<input type="submit" value="Filter" />
<a asp-action="Index">Full List</a>
</p>
<select class="chosen-select" multiple="multiple" name="filters" asp-for="filters"
asp-items="Model.filterModel.filters[0].values;"></select>
<input type="submit" />
<table class="table">
<thead>
<tr>
<th>
<a asp-controller="FileList" asp-action="Index" asp-route-searchString="#Model.searchString" asp-route-sortOrder="#ViewData["NameSortParm"]">
#Html.DisplayNameFor(model => model.files.FirstOrDefault().Name)
</a>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.files)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Guid">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Guid">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Guid">Delete</a>
</td>
</tr>
}
</tbody>
</table>
</form>
Model:
public class MasterModel
{
public FilterFileModel filterModel { get; set;}
public List<FileDisplay> files;
public string[] filters { get; set; }
public string searchString { get; set; }
}
Controller Index Method:
public async Task<IActionResult> Index(string sortOrder, string searchString, MasterModel model)
{
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
IGetFileListHandler fileListHandler = _restServiceFactory.CreateGetFileListHandler();
GetFileListRequest fileListRequest = new GetFileListRequest();
IGetFileListResponse response = await fileListHandler.ProcessRequest(fileListRequest);
var items = new List<FileDisplay>();
IGetFileAttributesHandler fileAttributesHandler = _restServiceFactory.CreateGetFileAttributesHandler();
GetFileAttributesRequest fileAttributesRequest = new GetFileAttributesRequest();
IGetFileAttributesResponse fileAttributesResponse = await fileAttributesHandler.ProcessRequest(fileAttributesRequest);
IGetFileFileAttributeHandler fileFileAttributesHandler = _restServiceFactory.CreateGetFileFileAttributeHandler();
GetFileFileAttributeRequest fileFileAttributesRequest = new GetFileFileAttributeRequest();
IGetFileFileAttributeResponse fileFileAttributesResponse = await fileFileAttributesHandler.ProcessRequest(fileFileAttributesRequest);
var fileFileAttribute = fileFileAttributesResponse.FileFileAttributes;
IEnumerable<Entities.Public.Interfaces.IFile> responseFilteredFiles = response.Files;
FilterFileModel fileFilter = new FilterFileModel();
fileFilter.filters = new List<FileFilter>();
if (!ReferenceEquals(fileAttributesResponse, null) && !ReferenceEquals(fileAttributesResponse.Values, null))
{
fileFilter.types = fileAttributesResponse.Values.Select(s => s.Type).Distinct().ToList(); // query fileattribute repo to get all types of filters
foreach (var type in fileFilter.types)
{
FileFilter filter = new FileFilter();
filter.type = type;
filter.values = fileAttributesResponse.Values.Where(s => s.Type == type).Select(s => new SelectListItem()
{
Value = s.Value,
Text = s.Value
}).Distinct().ToList();
fileFilter.filters.Add(filter);
}
}
if (!ReferenceEquals(response, null) && !ReferenceEquals(response.Files, null))
{
if (!String.IsNullOrEmpty(searchString))
{
responseFilteredFiles = responseFilteredFiles.Where(s => s.FileName.Contains(searchString));
model.searchString = searchString;
}
switch(sortOrder)
{
case "name_desc":
responseFilteredFiles = responseFilteredFiles.OrderByDescending(s => s.FileName);
break;
default:
responseFilteredFiles = responseFilteredFiles.OrderBy(s => s.FileName);
break;
}
}
if (model.filters != null)
{
if (model.filters.Length != 0)
{
IEnumerable<int> attributeIds = fileAttributesResponse.Values.Where(s => model.filters.Contains(s.Value)).Select(s => s.FileAttributeId);
IEnumerable<int> fileIds = fileFileAttribute.Where(s => attributeIds.Contains(s.FileAttributeId)).Select(s => s.FileId);
responseFilteredFiles = responseFilteredFiles.Where(s => fileIds.Contains(s.FileId));
}
}
foreach (var item in responseFilteredFiles)
{
var file = new FileDisplay()
{
Name = item.FileName,
Guid = item.Guid,
FileId = item.FileId
};
items.Add(file);
}
model.filterModel = fileFilter;
model.files = items;
return View(model);
}
The expected result is that the filter and search data persists when a user changes the sort. The actual results are only the search persists, I don't care about the sort persisting when the filters or search are changed.
I have a reservation system in which the date of the reservation is set by DateFrom - DateTo properties range. Now I want to assign the .alert class to those reservations, which are about to expire (1 day to expiration).
The problem is that If a reservation is about to expire, not only this reservation has .alert class set but also all other reservations, so all <tr> are red even though only one is supposed to. How to bind It only to current reservation?
Condition
foreach(Reservation r in res)
{
bool varovani;
if (r.DateTo.AddDays(-1).Day <= DateTime.Now.Day)
{
varovani = true;
}
else
{
varovani = false;
}
ViewBag.Varovani = varovani;
}
Table in View
<tbody>
#foreach (Reservation r in Model)
{
string alertClass = "";
if (ViewBag.Varovani == true)
{
alertClass = "danger";
}
else
{
alertClass = "";
}
<tr class="#alertClass">
<td>#r.Reserved.Id</td>
<td>#r.Name</td>
<td>#r.DateFrom</td>
<td>#r.DateTo</td>
<td>
#Ajax.ActionLink("Detail", "Detail", "Skies", new { id = r.Reserved.Id }, new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "modalContent", OnBegin = "openModalWindow" })
</td>
<td>
#Html.ActionLink("Edit", "Edit", "Reservation", new { id = r.Id }, null)
#Html.ActionLink("Delete", "Delete", "Reservation", new { id = r.Id }, new { onclick = "return confirm('Přejete si opravdu smazat tuto výpujčku? " + r.Name + "');" })
</td>
</tr>
}
</tbody>
The reason this is happening is because ViewBag.Varovani is a single bool value. So every time you iterate through you overwrite the "Varovani" bool value. What you want to do is add a property to you Reservation class:
public class Reservation
{
//Rest of class
public bool Varovani => DateTo.AddDays(-1).Day <= DateTime.Now.Day;
}
Then in your view:
<tbody>
#foreach (Reservation r in Model)
{
<tr class="#(r.Varovani ? "danger" : "")">
<td>#r.Reserved.Id</td>
<td>#r.Name</td>
<td>#r.DateFrom</td>
<td>#r.DateTo</td>
<td>
#Ajax.ActionLink("Detail", "Detail", "Skies", new { id = r.Reserved.Id }, new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "modalContent", OnBegin = "openModalWindow" })
</td>
<td>
#Html.ActionLink("Edit", "Edit", "Reservation", new { id = r.Id }, null)
#Html.ActionLink("Delete", "Delete", "Reservation", new { id = r.Id }, new { onclick = "return confirm('Přejete si opravdu smazat tuto výpujčku? " + r.Name + "');" })
</td>
</tr>
}
</tbody>
Alternatively you could perform the logic in your view (although I would not recommend it unless you cannot modify the Reservation class):
#foreach (Reservation r in Model)
{
string alertClass = "";
if (r.DateTo.AddDays(-1).Day <= DateTime.Now.Day)
{
alertClass = "danger";
}
else
{
alertClass = "";
}
//Rest of your original Razor
Disclaimer
I have no idea what "Varovani" means, so only use that as your property name if it describes your logic properly.
I try to add my files into DropDownList, all my files with the relevant property already return by the controller:
// GET: /WebMail/
public ActionResult Index()
{
var fileNameList = db.Captures.ToList().Where(x => x.robotFamily == "WebMail");
//return View(db.Captures.ToList().Where(x => x.robotFamily == "WebMail"));
ViewBag.Files = fileNameList;
return View();
}
Index.cshtml
#model IEnumerable<AutomationCapturesMVC.Models.Capture>
#{
//ViewBag.Title = "Index";
}
<table class="table">
<tr>
<th style="font-size: 20px">
#Html.DisplayNameFor(model => model.fileName)
</th>
<th></th>
</tr>
#Html.DropDownList("Id", (IEnumerable<AutomationCapturesMVC.Models.Capture>)ViewBag.Files, new { id = "WebMail", #class = "btn dropdown-toggle" })
#foreach (var item in Model)
{
<tr>
<td style="font-size: 15px">
#Html.DisplayFor(modelItem => item.fileName)
</td>
<td>
#Html.ActionLink("File Details", "Details", new { id = item.id })
</td>
</tr>
}
</table>
this is my page error:
http://s21.postimg.org/983eokpfq/1231231313.jpg
How about the following?
In controller
public ActionResult Index()
{
var fileNames = GetDatabaseFileNames();
var fileNameList = fileNames.Select(d => new SelectListItem { Text = d.FileName, Value = d.FileName.ToString() }).ToList();
ViewBag.Files = fileNameList;
return View();
}
In View
#Html.DropDownList("DatabaseFiles", (IEnumerable<SelectListItem>)ViewBag.Files, new { id = "DatabaseFiles", #class = "btn dropdown-toggle" })