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.
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 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>
}
I would like to add a simple search function in my simple database.
I have completed an add, edit & delete function. I have difficulty dealing with the search function.
Currently I have a search box and I have thought of the proper SQL query to execute in the database so I can get a simple result.
I have difficulty in passing the textbox field to the controller so that it can be used as search query in the SQL Database, and then bringing it back to the view for the search results.
I am an ASP.NET MVC beginner. Please help. Thank you very much!
Here is my work so far:
View
#model IEnumerable<SampleReg.Models.Course>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm("Search", "Course", FormMethod.Post))
{
<input type="text" name="txtsearch" value=" " />
<input type="submit" name="btnsubmit" value="submit" />
}
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.crs_ID)
</th>
<th>
#Html.DisplayNameFor(model => model.crs_Course)
</th>
<th>
#Html.DisplayNameFor(model => model.crs_Major)
</th>
<th>
#Html.DisplayNameFor(model => model.crs_Spec)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.crs_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.crs_Course)
</td>
<td>
#Html.DisplayFor(modelItem => item.crs_Major)
</td>
<td>
#Html.DisplayFor(modelItem => item.crs_Spec)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.crs_ID }) |
#Html.ActionLink("Details", "Details", new { id = item.crs_ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.crs_ID })
</td>
</tr>
}
</table>
Controller
public ActionResult Index()
{
return View(GetAllCourse(""));
}
[HttpPost, ActionName("Search")]
[ValidateAntiForgeryToken]
public ActionResult Search(string GetAllCourse) {
string search = Request.Form["txtsearch"].ToString();
//GetAllCourse("search");
return View();
}
#region PRIVATE FUNCTIONS
private List<Course> GetAllCourse(string search)
{
//DECLARATION AND INIT
SqlConnection oCon = null;
SqlCommand oCmd = null;
SqlDataReader oDr = null;
List<Course> oList = null;
string SqlCon = #"Data Source=IT-MARICOR\LOCAL;Initial Catalog=INTERN;User ID=sa;Password=aaa";
try
{
//SET CONNECTION
oCon = new SqlConnection();
oCon.ConnectionString = SqlCon;
if (oCon.State == System.Data.ConnectionState.Closed)
{
oCon.Open();
}
//SET COMMAND
oCmd = new SqlCommand();
oCmd.Connection = oCon;
oCmd.CommandType = System.Data.CommandType.Text;
oCmd.CommandText = "SELECT * FROM Course " + (search == "" ? "" : " WHERE crs_Course LIKE '% " + search + "%'");
oDr = oCmd.ExecuteReader();
if (oDr.HasRows)
{
oList = new List<Course>();
while (oDr.Read())
{
Course oCourse = new Course();
oCourse.crs_ID = Convert.ToInt32(oDr["crs_ID"].ToString());
oCourse.crs_Course = oDr["crs_Course"].ToString();
oCourse.crs_Major = oDr["crs_Major"].ToString();
oCourse.crs_Spec = oDr["crs_Specialization"].ToString();
oList.Add(oCourse);
}
return oList;
}
return null;
}
catch (Exception ex)
{
throw ex;
}
finally
{
//CLEAN UP RESOURCES
oCon.Close();
oCon = null;
}
}
#endregion
Here is what it looks like:
OR you can take help of jquery ajax method.
give one id to text box.
var Url = "/Course/Search",
var textvalue= $('#textboxid').val(),
$.ajax({
url: Url ,
data: { GetAllCourse: textvalue},
type: "GET",
url: Path,
success: function (result) {
}
});
I am newbie in asp.net mvc.
I have 2 cascading dropdownlist and 1 file input on my page.
I made cascading dropdownlists following this tutorial. But when I trying to pass value to controller, there is an error System.ArgumentException, null parameter. I looked up the list of parameters using Firebug, but I can't find value of second dropdown at all.
My controller code is below:
public ActionResult Index()
{
List<SelectListItem> branchNames = new List<SelectListItem>();
FormatModel fmtModel = new FormatModel();
List<branch> branches = db.branch.ToList();
branches.ForEach(x =>
{
branchNames.Add(new SelectListItem { Text = x.name, Value = x.id.ToString() });
}
);
fmtModel.BranchNames = branchNames;
return View(fmtModel);
}
[HttpPost]
public ActionResult GetPaymentSystem(string branchId)
{
int intBranchId;
List<SelectListItem> paymentSystemNames = new List<SelectListItem>();
if (!string.IsNullOrEmpty(branchId))
{
intBranchId = Convert.ToInt32(branchId);
List<paymentSysDTO> paymentSystems =
(from ps in db.paymentSys
join ps_br in db.br_ps_format on ps.id equals ps_br.ps_id
join br in db.branch on ps_br.branch_id equals br.id
where br.id == intBranchId
select new paymentSysDTO
{
id = ps.id,
name = ps.name,
code = ps.code
}
).ToList();
paymentSystems.ForEach(x =>
{
paymentSystemNames.Add(new SelectListItem { Text = x.name, Value = x.id.ToString() });
}
);
}
return Json(paymentSystemNames, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Index(int BranchNames, int PaymentSystemNames, HttpPostedFileBase file)
{
//controller code
}
View code:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<legend>Введите данные:</legend>
<table>
<tr>
<td>
<label>Филиал</label>
</td>
<td>
#Html.DropDownListFor(x => x.BranchNames, Model.BranchNames, "Выбрать", new { id = "ddlBranch" })
</td>
</tr>
<tr>
<td>
<label>Платежная система/Банк</label>
</td>
<td id="PaymentSystem">
#Html.DropDownListFor(x => x.PaymentSystemNames, new List<SelectListItem>(), "Выбрать", new { #id = "ddlPaymentSystem" })
</td>
</tr>
<tr>
<td>
<input id="InputFile" type="file" name="file" />
</td>
</tr>
<tr>
<td>
<input id="ConvertButton" type="submit" value="Конвертировать" />
</td>
</tr>
</table>
}
#if (null != TempData["msg"])
{
#Html.Raw(TempData["msg"])
}
<script type="text/javascript">
$(function () {
$('#ddlBranch').change(function () {
$.ajax({
type: 'POST',
url: "/Home/GetPaymentSystem",
data: { branchID: $('#ddlBranch').val() },
datatype: "json",
traditional: true,
success: function (data) {
var paymentSystem = "<select id='ddlPaymentSystem'>";
paymentSystem = paymentSystem + '<option value ="">Select</option>';
for (var i = 0; i < data.length; i++)
{
paymentSystem = paymentSystem + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
paymentSystem = paymentSystem + '</select>';
$('#PaymentSystem').html(paymentSystem);
}
cas
});
});
});
</script>
Sorry for my English and thanks for ur help.
I have three dropdownlist - Project, Sprint, Story.
Sprint dropdownlist will be binded on the basis of selected Project, Story dropdownlist will be binded on the basis of selected Sprint. On the basis of selected Story, i want to show a webgrid.
what i m doing is:
my Project dropdownlist is on the main view page, Sprint dropdownlist, and Story dropdownlist are two diferent partial views. When i select from Project, selected value is taken in jquery and passed to controller as:
$('#Project').change(function (e) {
e.preventDefault();
var selectedVal = $("#Project").val();
$.ajax({
url: "/Task/BindSprintList",
data: { projectTitle: selectedVal },
type: 'Get',
success: function (result) {
$('#ViewGrid').html(result);
},
error: function () {
alert("something seems wrong");
}
});
});
Now Sprint Dropdown list appears. When i select from Sprint, selected value is taken in jquery and passed to controller as:
$('#Sprint').change(function (e) {
e.preventDefault();
var selectedProjectVal = $("#Project").val();
var selectedSprintVal = $("#Sprint").val();
$.ajax({
url: "/Task/BindStoryList",
data: { projectTitle: selectedProjectVal, sprintTitle: selectedSprintVal },
type: 'Get',
success: function (result) {
$('#ddlStory').html(result); },
error: function (err) {
alert("something seems wrong "+ err);
}
});
});
but now Story Dropdownlist is not displaying.
MainPage.cshtml
<table>
#{
if (ViewBag.ProjectList != null)
{
<tr>
<td>
<h4>SELECT PROJECT </h4>
</td>
<td>
#Html.DropDownList("Project", new SelectList(ViewBag.ProjectList, "Value", "Text"), " -- Select -- ")
</td>
</tr>
}
if (ViewBag.SprintList != null)
{
Html.RenderPartial("PartialSprintDropDown", Model.AsEnumerable());
}
if (ViewBag.StoryList != null)
{
Html.RenderPartial("PartialStoryDropDown", Model.AsEnumerable());
}
}
</table>
PartialSprintDropDown.cshtml
<table>
<tr>
<td>
<h4>SELECT SPRINT</h4>
</td>
<td>
#Html.DropDownList("Sprint", new SelectList(ViewBag.SprintList, "Value", "Text"), " -- Select -- ")
</td>
</tr>
</table>
<script src="~/Script/Task/IndexTask.js" type="text/javascript"></script>
PartialStoryDropDown.cshtml
<div id="ddlStory">
<table>
<tr>
<td>
<h4>SELECT STORY</h4>
</td>
<td>
#Html.DropDownList("Story", new SelectList(ViewBag.StoryList, "Value", "Text"), " -- Select -- ")
</td>
</tr>
</table>
</div>
<script src="~/Script/Task/IndexTask.js" type="text/javascript"></script>
Can anyone suggest me that why Story DropdownList is not displaying. Even when i m debbuging PartialStoryDropDown.cshtml, "ViewBag.StoryList" contains data as expected, but not showing on the page.
I m containing my data in Viewbag.SprintList and Viewbag.StoryList.
SprintDropdownlist is displaying.
How to resolve this ?
BindSprintList()
public ActionResult BindSprintList(string projectTitle)
{
try
{
string Owner = Session["UserName"].ToString();
int? ProjectId = GetProjectID(projectTitle);
var ddlSprint = new List<string>();
List<SelectListItem> items = new List<SelectListItem>();
var querySprint = (from sp in entities.Sprints
where sp.Project_ID == ProjectId && sp.Sprint_Status != "Completed"
select sp).ToList();
foreach (var item in querySprint.ToList())
{
SelectListItem li = new SelectListItem
{
Value = item.Sprint_Title,
Text = item.Sprint_Title
};
items.Add(li);
}
IEnumerable<SelectListItem> List = items;
ViewBag.SprintList = new SelectList(List, "Value", "Text");
}
catch (Exception e)
{
var sw = new System.IO.StreamWriter(filename, true);
sw.WriteLine("Date :: " + DateTime.Now.ToString());
sw.WriteLine("Location :: AgileMVC >> Controllers >> TaskController.cs >> public ActionResult BindSprintList(string projectTitle)");
sw.WriteLine("Message :: " + e.Message);
sw.WriteLine(Environment.NewLine);
sw.Close();
}
return PartialView("PartialSprintDropDown", ViewBag.SprintList);
}
BindStoryList()
public ActionResult BindStoryList(string projectTitle, string sprintTitle)
{
try
{
string Owner = Session["UserName"].ToString();
int? ProjectId = GetProjectID(projectTitle);
int? SprintId = GetSprintID(ProjectId, sprintTitle);
var ddlStory = new List<string>();
List<SelectListItem> items = new List<SelectListItem>();
var queryStory = (from st in entities.Stories
join spss in entities.SprintStories on st.Story_ID equals spss.Story_ID
where spss.Sprint_ID == SprintId && spss.Project_ID == ProjectId
select st).ToList();
foreach (var item in queryStory.ToList())
{
SelectListItem li = new SelectListItem
{
Value = item.Story_Title,
Text = item.Story_Title
};
items.Add(li);
}
IEnumerable<SelectListItem> List = items;
ViewBag.StoryList = new SelectList(List, "Value", "Text");
}
catch (Exception e)
{
var sw = new System.IO.StreamWriter(filename, true);
sw.WriteLine("Date :: " + DateTime.Now.ToString());
sw.WriteLine("Location :: AgileMVC >> Controllers >> TaskController.cs >> public ActionResult BindStoryList()");
sw.WriteLine("Message :: " + e.Message);
sw.WriteLine(Environment.NewLine);
sw.Close();
}
return PartialView("PartialStoryDropDown", ViewBag.StoryList);
}
I think I see your problem - ddlStory div comes as part of result. So when you say $('#ddlStory'), it doesn't do anything since its not on the page yet.
I think in your main page, you need to have a placeholder for ddlStory and replace that placeholder's html. Something like $('#ddlStoryWrapper').html(result) where ddlStoryWrapper is just an empty div on the page.