I have a view, which shows a list of items consumed in a div and other details of a complaint in another div. Now, these items consumed div can have multiple records against a complaint. How to add new records and then refresh the div while still showing the original view. How to work around the problem. I did try to use modal popup but after submission and record update in the table, it's still showing the modal, whereas it needs to refresh the view itself.
This join view has edit option to set status, which leads to the problem view mentioned above.
In the status set view , i have multiple data such as id etc. in one div, Another div which contains the list of materials consumed so far. This div where consumption details are loaded as a list needs to be updated , as in new records to be updated and the updated view should be generated.
I need to dynamically add new material in the other div based on dropdown selection(hide/Show). and after submission, the tables needs to be updated.
public ActionResult StatusEdit(int id, int statuscode, string statusaction, int regid, short appid, short dep, short com )
{
DisplayEC dn = new DisplayEC();
DbAccess da = new DbAccess();
dn.ComplnId = com;
dn.JobC = id;
///dn.MatId = mat;
///dn.StDate = sdate;
dn.DeptCode = dep;
dn.Appid = appid;
dn.statcode = statuscode;
dn.statacn = statusaction;
dn.Regid = regid;
dn.JbStsDate = DateTime.Now.ToString();
dn.DeptCode = Convert.ToByte(Session["departmentno"]);
dn.ListJobStatus = new List<System.Web.Mvc.SelectListItem>();
dn.ListJobStatus = da.GetAllJobStatus(dn.DeptCode, appid);
dn.ListJobHistory = new List<JobStatus>();
dn.ListJobMaterials = new List<DispJobMaterial>();
dn.JobCode = dn.JobC.ToString();
if ((dn.DeptCode > 0) && (!string.IsNullOrEmpty(dn.JobCode)))
{
dn.ListJobHistory = da.GetJobStatusHistory(dn.DeptCode, dn.Appid, Convert.ToInt32(dn.JobC));
dn.ListJobMaterials = da.GetMaterialsConsumed(dn.DeptCode, Convert.ToByte(dn.Appid), Convert.ToInt32(dn.JobC));
}
dn.ListMaterials = new List<System.Web.Mvc.SelectListItem>();
dn.ListMaterials = da.GetMaterialsByUserType(dn.DeptCode, dn.Appid, "DEPTUSER");
return View(dn);
}
View:
#using System.Web.Helpers
#model EC.ViewModels.DisplayEC
#{
Layout = "~/Views/Shared/_Layout1.cshtml";
}
<br />
<br />
<a style="cursor: pointer; font-size: 30px; color:darkblue" title="Home" class="fa fa-home pull-left" href="#Url.Action("JoinView", "Admin")"></a>
<a style="cursor: pointer; font-size: 30px; color:darkblue" title="Log Out" class="fa fa-sign-out pull-right" href="#Url.Action("Login", "Account")"></a>
<br /><br />
<h4 class="display-4" style="display: inline;">JOBCODE :: <span style="color:red">#Model.JobCode</span></h4>
<div class="mt-5">
#*#using (Html.BeginForm("StatusEdit", "Admin", FormMethod.Post, new { id = "StatusEdit", #class = "", role = "form" }))*#
#using (Html.BeginForm("StatusEdit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(x => x.JobC)
#Html.HiddenFor(x => x.JobCode)
#Html.HiddenFor(x => x.DeptCode)
#Html.HiddenFor(x => x.Appid)
#Html.HiddenFor(x => x.statcode)
#Html.HiddenFor(x => x.statacn)
#Html.HiddenFor(x => x.Regid)
#Html.HiddenFor(x => x.JbStsDate)
#Html.HiddenFor(x => x.Regid)
#*#Html.HiddenFor(x => x.JobStatusCode)*#
#Html.HiddenFor(x => x.ComplnId)
#Html.HiddenFor(x => x.MatId)
#Html.HiddenFor(x => x.StDate)
<div>
#if (TempData["notice"] != null)
{
<h4 class="alert alert-danger" id="successMessage">#TempData["notice"]</h4>
}
</div>
<table class="table table-borderless" style="width:100%">
<tbody>
<tr>
<td style="width:50%">
<div class="card">
<div class="card-header bg-secondary"><span style="font-weight:bold;color:white">JOB STATUS</span></div>
<div class="card-body">
<table class="table table-borderless" style="width:100%;margin-bottom:0;padding-bottom:0">
<tbody>
<tr>
<td style="width:30%">
<div class="form-group">
#Html.LabelFor(x => x.JobStatusCode, new { #class = "control-label label_text" })
<div>
#if (string.IsNullOrEmpty(Model.JobCode))
{
#Html.DropDownListFor(x => x.JobStatusCode, new SelectList(Model.ListJobStatus.ToList().Where(x => x.Value != "1").Where(x => x.Value != "2").Where(x => x.Value != "3").Where(x => x.Value != "6").Where(x => x.Value != "7").Where(x => x.Value != "5").ToList(), "Value", "Text", Model.JobStatusCode), new { #class = "form-control", #disabled = "true", id = "ddlCategory" })
}
else
{
#Html.DropDownListFor(x => x.JobStatusCode, new SelectList(Model.ListJobStatus.ToList().Where(x => x.Value != "1").Where(x => x.Value != "2").Where(x => x.Value != "3").Where(x => x.Value != "6").Where(x => x.Value != "7").Where(x => x.Value != "5").ToList(), "Value", "Text", Model.JobStatusCode), new { #class = "form-control", id = "ddlCategory" })
}
#Html.ValidationMessageFor(x => x.JobStatusCode)
</div>
</div>
</td>
<td style="width:20%">
<div class="form-group">
#Html.LabelFor(x => x.JbStsDate, new { #class = "control-label label_text" })
<div>
#Html.TextBoxFor(x => x.JbStsDate, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.JbStsDate)
</div>
</div>
</td>
<td style="width:30%">
<div class="form-group">
#Html.LabelFor(x => x.JobStatusRemark, new { #class = "control-label label_text" })
<div>
#Html.TextBoxFor(x => x.JobStatusRemark, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.JobStatusRemark)
</div>
</div>
</td>
<td style="width:20%">
<div class="form-group" style="padding-top: 30px;">
<button id="btnAddSts" type="button" disabled="disabled" class="btn btn-info pull-left"><i class="fa fa-plus-square"></i> Add Status</button>
</div>
</td>
</tr>
</tbody>
</table>
<table id="JbStsHtry" class="table table-responsive-md table-hover" style="width:100%">
<tbody>
#for (int i = 0; i < Model.ListJobHistory.Count; i++)
{
<tr class="h-divider_sts">
<td style="width:40%">
<span>#Html.DisplayFor(x => x.ListJobHistory[i].StatusText)</span>
</td>
<td style="width:20%">
<span>#Model.ListJobHistory[i].StatusDate.ToShortDateString()</span>
</td>
<td style="width:30%">
<span>#Html.DisplayFor(x => x.ListJobHistory[i].StatusRemarks)</span>
</td>
<td style="width:10%">
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</td>
<td style="width:50%" id="Other">
<div class="card">
<div class="card-header bg-secondary">
<span style="font-weight:bold;color:white">Material Consumed</span>
</div>
<div class="card-body">
<table class="table table-borderless table-responsive-md" style="width:100%;margin-bottom:0;padding-bottom:0">
<tbody>
<tr style="width:20%">
<th>#Html.LabelFor(x => x.JobMaterialId, new { #class = "control-label label_text" })</th>
<th> #Html.LabelFor(x => x.MatrlQty, new { #class = "control-label label_text" })</th>
</tr>
<tr>
<td style="width:40%">
<div class="form-group">
#*#Html.LabelFor(x => x.JobMaterialId, new { #class = "control-label label_text" })*#
<div>
#if (string.IsNullOrEmpty(Model.JobCode))
{
#Html.DropDownListFor(x => x.JobMaterialId, new SelectList(Model.ListMaterials, "Value", "Text", Model.JobMaterialId), new { #class = "form-control", #disabled = "true" })
}
else
{
#Html.DropDownListFor(x => x.JobMaterialId, new SelectList(Model.ListMaterials, "Value", "Text", Model.JobMaterialId), new { #class = "form-control" })
}
#Html.ValidationMessageFor(x => x.JobMaterialId)
</div>
</div>
</td>
<td style="width:30%">
<div class="form-group">
#*#Html.LabelFor(x => x.MatrlQty, new { #class = "control-label label_text" })*#
<div>
#Html.TextBoxFor(x => x.MatrlQty, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.MatrlQty)
</div>
</div>
</td>
<td style="width:30%">
<div class="form-group" style="padding-top: 30px;">
<button id="btnAdd" class="btn btn-info pull-left"><i class="fa fa-plus-square"></i> Add Material</button>
</div>
</td>
</tr>
</tbody>
</table>
#*<table id="JbMatrl" class="table table-responsive-md table-hover" style="width:100%">*#
<table id="JbMatrl" class="table table-responsive-md table-hover" style="width:100%">
<tbody>
#for (int i = 0; i < Model.ListJobMaterials.Count; i++)
{
<tr class="h-divider_sts">
<td style="width:50%">
#Html.DisplayFor(x => x.ListJobMaterials[i].MaterialText)
</td>
<td style="width:50%">
#Html.DisplayFor(x => x.ListJobMaterials[i].MaterialQty)
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</td>
<td style="width:50%" id="Other2">
</td>
</tr>
</tbody>
</table>
<div class="form-group" style="padding-top: 30px;">
<button type="submit" class="btn btn-info pull-left"><i class="fa fa-plus-square"></i> Submit</button>
</div>
}
</div>
<br />
\\\\\\\\
<script type="text/javascript">
$(document).ready(function () {
$("#ddlCategory").change(function () {
var e = document.getElementById("ddlCategory");
var value = e.options[e.selectedIndex].text;
if (value == "Assignment Cancelled") {
$('#Other').hide();
$('#Other2').show();
} else {
$('#Other').show();
$('#Other2').hide();
}
});
});
</script>
Related
I have an initial table in the Index Get method where I query all the columns I want to display, with GetAll() method. Here I also load the drop-down menus where I select the parameters.
/********INDEX GET*********/
[HttpGet]
public IActionResult Index()
{
BudgetVM = new BudgetViewModel()
{
FBudget = new FBudget(),
YearsList = _unitOfWork.Budget.GetYearsListForDropdown(),
CompanyList = _unitOfWork.Budget.GetCompanyListForDropDown(),
CustomerList = _unitOfWork.Budget.GetCustomerListForDropDown(),
ProductGroupList = _unitOfWork.Budget.GetProductGroupListForDropDown(),
LicensingAreaList = _unitOfWork.Budget.GetLicensingAreaListForDropDown(),
PharmaFormList = _unitOfWork.Budget.GetPharmaFormListForDropDown(),
LedgerScenarioList = _unitOfWork.Budget.GetLedgerScenarioListForDropDown(),
CurrencyList = _unitOfWork.Budget.GetCurrencyListForDropdown(),
//Lista di tutti i record
RecordsList = _unitOfWork.Budget.GetAll(includeProperties: "ItemMaster,Customer")
};
return View(BudgetVM);
}
Here is the view that will send the parameters to the Index Post method:
#model SalesBudget.Models.ViewModels.BudgetViewModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<form method="post" asp-controller="Budget" asp-action="Index">
<div class="row">
<div class="col-6">
<br />
<h2 class="text-primary">Filter by</h2>
</div>
</div>
<div class="row">
<div class="col">
<div class="dropdown">
#*Parameter1: what I want to save in the db
Parameter2: actual list of items (dropdown menu)
Parameter3: default that I see in the dropdown
Parameter4: classes that I want to add*#
<!--BLOCCA IL PROGRAMMA IN DELETE-->
#Html.DropDownListFor(m => m.FBudget.CompanyId,
Model.CompanyList,
"--Company--",
new { #class = "form-control" })
</div>
<br />
<div class="dropdown">
#Html.DropDownListFor(m => m.FBudget.CustomerId,
Model.CustomerList,
"--Customer--",
new { #class = "form-control" })
</div>
<br />
</div>
<div class="col">
<div class="dropdown">
#Html.DropDownListFor(m => m.FBudget.Customer.LicensingArea,
Model.LicensingAreaList,
"--Licensing Area--",
new { #class = "form-control" })
</div>
<br />
<div class="dropdown">
#Html.DropDownListFor(m => m.FBudget.Year,
Model.YearsList,
"--Year--",
new { #class = "form-control" })
</div>
<br />
</div>
<div class="col">
<div class="dropdown">
#Html.DropDownListFor(m => m.FBudget.ItemMaster.ProductGroupId,
Model.ProductGroupList,
"--Product Group--",
new { #class = "form-control" })
</div>
<br />
<div class="dropdown">
#Html.DropDownListFor(m => m.FBudget.ItemMaster.PharmaFormId,
Model.PharmaFormList,
"--Pharma Form--",
new { #class = "form-control" })
</div>
<br />
</div>
<div class="col">
<div class="dropdown">
#Html.DropDownListFor(modelItem => modelItem.FBudget.Currency,
Model.CurrencyList,
"--Currency--",
new { #class = "form-control" })
</div>
<br />
<div class="dropdown">
#Html.DropDownListFor(m => m.FBudget.LedgerTypeId,
Model.LedgerScenarioList,
"--Scenario--",
new { #class = "form-control" })
</div>
<br />
</div>
<div class="dropdown">
<button type="submit" class="btn btn-primary form-control">Go</button>
</div>
</div>
</form>
<hr />
<div class="row">
<div class="col-6">
<h2 class="text-primary">Budget List</h2>
</div>
<div class="col-6">
<a asp-action="Upsert" class="btn btn-primary float-end"><i class="fas fa-plus"></i> Create New Budget</a>
</div>
</div>
<br />
<br />
<table class="table">
<thead>
<tr>
<th>
Customer
</th>
<th>
Decription
</th>
<th>
Curr
</th>
<th>
FoC
</th>
<th>
UM
</th>
<th>
Price
</th>
<th>
Quantity
</th>
<th>
Total amount
</th>
<th>
Action
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.RecordsList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Customer.CustomerName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ItemMaster.ItemDescription)
</td>
<td>
#Html.DisplayFor(modelItem => item.Currency)
</td>
<td>
#Html.DisplayFor(modelItem => item.FreeOfCharge)
</td>
<td>
#Html.DisplayFor(modelItem => item.UnitOfMeasure)
</td>
<td>
#Html.DisplayFor(modelItem => item.UnitPrice)
</td>
<td>
#Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
#Html.DisplayFor(modelItem => item.TotalAmount)
</td>
<td>
<a asp-action="Upsert" asp-route-id="#item.BudgetId">Edit</a> |
<a asp-action="Delete" asp-route-id="#item.BudgetId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
And here is the Index Post method in the Controller:
/********INDEX POST*********/
[HttpPost]
public IActionResult Index(BudgetViewModel budget)
{
BudgetVM = new BudgetViewModel()
{
FBudget = new FBudget(),
YearsList = _unitOfWork.Budget.GetYearsListForDropdown(),
CompanyList = _unitOfWork.Budget.GetCompanyListForDropDown(),
CustomerList = _unitOfWork.Budget.GetCustomerListForDropDown(),
ProductGroupList = _unitOfWork.Budget.GetProductGroupListForDropDown(),
LicensingAreaList = _unitOfWork.Budget.GetLicensingAreaListForDropDown(),
PharmaFormList = _unitOfWork.Budget.GetPharmaFormListForDropDown(),
LedgerScenarioList = _unitOfWork.Budget.GetLedgerScenarioListForDropDown(),
CurrencyList = _unitOfWork.Budget.GetCurrencyListForDropdown(),
//Here isd where I try to filter data
RecordsList = _unitOfWork.Budget.GetAll(
filter: b => b.Year == budget.FBudget.Year
&& b.CompanyId == budget.FBudget.CompanyId
&& b.CustomerId == budget.FBudget.CustomerId
&& b.Customer.LicensingArea == budget.FBudget.Customer.LicensingArea
&& b.ItemMaster.ProductGroupId == budget.FBudget.ItemMaster.ProductGroupId
&& b.ItemMaster.PharmaFormId == budget.FBudget.ItemMaster.PharmaFormId
&& b.Currency == budget.FBudget.Currency
&& b.LedgerTypeId == budget.FBudget.LedgerTypeId
, includeProperties: "ItemMaster,Customer")
};
//return View(budget);
return View(BudgetVM);
}
Naturally with the logical operator && all fields must be inserted, otherwise the query result will be empty. How can I make these parameters optional, so that if I select only one filter (dropdown) the query is made only on that field, excluding the others?
Here is the GetAll() method:
public IEnumerable<T> GetAll(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
//include properties will be comma seperated
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
return query.ToList();
}
Thanks
You can either use something like PredicateBuilder to build the filter, or build it yourself using the System.Linq.Expressions namespace.
For example, assuming any filter properties which are not set will be null:
public static Expression<Func<Budget, bool>> BuildFilter(BudgetViewModel budget)
{
var b = Expression.Parameter(typeof(Budget), "b");
var filterParts = new List<Expression>();
if (budget.FBudget.Year is {} year)
{
var bugetYear = Expression.Property(b, nameof(Budget.Year);
var testYear = Expression.Constant(year);
filterParts.Add(Expression.Equal(budgetYear, testYear));
}
if (budget.FBudget.CompanyId is {} companyId)
{
var budgetCompanyId = Expression.Property(b, nameof(Budget.CompanyId));
var testCompanyId = Expression.Constant(companyId);
filterParts.Add(Expression.Equal(budgetCompanyId, testCompanyId));
}
if (budget.FBudget.CustomerId is {} customerId)
{
var budgetCustomerId = Expression.Property(b, nameof(Budget.CustomerId));
var testCustomerId = Expression.Constant(customerId);
filterParts.Add(Expression.Equal(budgetCustomerId, testCustomerId));
}
if (budget.FBudget.Customer.LicensingArea is {} licensingArea)
{
var budgetCustomer = Expression.Property(b, nameof(Budget.Customer));
var budgetLicensingArea = Expression.Property(budgetCustomer, nameof(Customer.LicensingArea));
var testLicensingArea = Expression.Constant(licensingArea);
filterParts.Add(Expression.Equal(budgetLicensingArea, testLicensingArea));
}
if (budget.FBudget.ItemMaster.ProductGroupId is {} productGroupId)
{
var budgetItemMaster = Expression.Property(b, nameof(Budget.ItemMaster));
var budgetProductGroupId = Expression.Property(budgetItemMaster, nameof(ItemMaster.ProductGroupId));
var testProductGroupId = Expression.Constant(productGroupId);
filterParts.Add(Expression.Equal(budgetProductGroupId, testProductGroupId));
}
if (budget.FBudget.ItemMaster.PharmaFormId is {} pharmaFormId)
{
var budgetItemMaster = Expression.Property(b, nameof(Budget.ItemMaster));
var budgetPharmaFormId = Expression.Property(budgetItemMaster, nameof(ItemMaster.PharmaFormId));
var testPharmaFormId = Expression.Constant(pharmaFormId);
filterParts.Add(Expression.Equal(budgetPharmaFormId, testPharmaFormId));
}
if (budget.FBudget.Currency is {} currency)
{
var budgetCurrency = Expression.Property(b, nameof(Budget.Currency));
var testCurrency = Expression.Constant(currency);
filterParts.Add(Expression.Equal(budgetCurrency, testCurrency));
}
if (budget.FBudget.LedgerTypeId is {} ledgerTypeId)
{
var budgetLedgerTypeId = Expression.Property(b, nameof(Budget.LedgerTypeId));
var testLedgerTypeId = Expression.Constant(ledgerTypeId);
filterParts.Add(Expression.Equal(budgetLedgerTypeId, testLedgerTypeId));
}
if (filterParts.Count == 0) return null;
var body = filterParts.Aggregate(Expression.AndAlso);
return Expression.Lambda<Func<Budget, bool>>(body, b);
}
I'm trying to add an orderable table to my view. The sorting works when doing it in the View New.cshtml. It uses jQuerys sortable. If I add some instructions (1-5 in this case) I can move them around thanks to the sortable script. But when I try to add a new instruction after the reordering, the order change from:
to
I guess it has something to do with the hidden form
#Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { #id = "Number"})
It needs to update its value when I reorder the fields in the sortable table.
What am I missing here?
RecipeController.cs
public ActionResult Create(NewRecipeViewModel viewModel, string command)
{
//...more code...
var instructionList = new List<Instruction>();
if (viewModel.Recipe.Instructions != null)
{
for (int i = 0; i < viewModel.Recipe.Instructions.Count; i++)
{
var instruction = new Instruction
{
Id = viewModel.Recipe.Instructions[i].Id,
Name = viewModel.Recipe.Instructions[i].Name,
Number = viewModel.Recipe.Instructions[i].Number
};
instructionList.Add(instruction);
}
}
if (command.Equals("AddInstruction"))
{
var instruction = new Instruction
{
Name = viewModel.NewInstruction.Name,
Number = viewModel.Recipe.Instructions.Count + 1
};
recipe.Instructions.Add(instruction);
viewModel.Recipe = recipe;
return View("New", viewModel);
}
//...more code...
}
New.cshtml
<div class="form-group" style="margin-top: 170px;">
<label class="col-md-2 control-label">
Lägg till instruktion:
</label>
<div class="col-md-10">
#Html.TextBoxFor(m => m.NewInstruction.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group" style="margin-top: 300px;">
<label class="col-md-2 control-label">
</label>
<div class="col-md-10">
<button type="submit" name="command" value="AddInstruction" class="btn btn-primary">Add instruction</button>
</div>
</div>
<div class="form-group" style="margin-top: 100px;">
<label class="col-md-2 control-label">
Instructions:
</label>
<div class="col-md-10">
<table class="table table-bordered table-hover pagin-table" style="margin-top: 10px">
<thead>
<tr bgcolor="#f5f5f5">
<th>Order:</th>
<th>Instruction:</th>
</tr>
</thead>
<tbody id="sortable">
#if (Model.Recipe.Instructions != null)
{
for (int i = 0; i < Model.Recipe.Instructions.Count; i++)
{
<tr>
#Html.HiddenFor(m => Model.Recipe.Instructions[i].Id)
<td class="order">
#Model.Recipe.Instructions[i].Number
#Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { #id = "Number"})
</td>
<td>
#Model.Recipe.Instructions[i].Name
#Html.HiddenFor(m => m.Recipe.Instructions[i].Name)
</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#sortable').sortable({
update : function(event, ui) {
$('td.order').each(function(index) {
var order = index + 1;
$(this).find('span').text(order);
$(this).find('.Number').val(order);
});
}
});
});
</script
EDIT:
Added
instructionList.Sort((s1, s2) => s1.Number.CompareTo(s2.Number));
to RecipeController.cs. The rest is credit to Stephen Muecke.
RecipeController.cs
public ActionResult Create(NewRecipeViewModel viewModel, string command)
{
//...more code...
var instructionList = new List<Instruction>();
if (viewModel.Recipe.Instructions != null)
{
for (int i = 0; i < viewModel.Recipe.Instructions.Count; i++)
{
var instruction = new Instruction
{
Id = viewModel.Recipe.Instructions[i].Id,
Name = viewModel.Recipe.Instructions[i].Name,
Number = viewModel.Recipe.Instructions[i].Number
};
instructionList.Add(instruction);
}
instructionList.Sort((s1, s2) => s1.Number.CompareTo(s2.Number));
}
//...more code...
}
New.cshtml
#* More code *#
<td class="order">
<span>#Model.Recipe.Instructions[i].Number</span>
#Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new {#class = "Number"})
</td>
#* More code *#
<script type="text/javascript">
$(document).ready(function() {
$('#sortable').sortable({
update : function(event, ui) {
$('td.order').each(function(index) {
var order = index + 1;
$(this).find('span').text(order);
$(this).find('.Number').val(order);
});
}
});
});
</script
Your selector in the update function is incorrect and would return undefined (you are missing the # (id selector) and in anycase the $ creates a jQuery object, so it would be .val(...), not value=....
However using $('#Number').val(index + 1) will not work correctly since it would only ever update the first element with id="Number". Duplicateid` attributes are invalid html.
Use a class name and relative selectors instead. Change the html to
<td class="order">
<span>#Model.Recipe.Instructions[i].Number</span>
#Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { #class = "Number"})
</td>
and then the script to
$('#sortable').sortable({
update : function(event, ui) {
$('td.order').each(function(index) {
var order = index + 1;
$(this).find('span').text(order );
$(this).find('.Number').val(order );
});
}
});
In your markup, change Model to your projected variable m within your 'Html.HiddenFor()' HTML helpers.
<tr>
#Html.HiddenFor(m => m.Recipe.Instructions[i].Id)
<td class="order">
#Model.Recipe.Instructions[i].Number
#Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { #id = "Number"})
</td>
<td>
#Model.Recipe.Instructions[i].Name
#Html.HiddenFor(m => m.Recipe.Instructions[i].Name)
</td>
</tr>
I have faced a problem which is can't save the record into the database. I have 3 model in one view. I have done the view and getting error about this
An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Validation failed for one or more entities.
See 'EntityValidationErrors' property for more details.
here is my view
<div class="container">
<div class="row">
<div class="col-lg-12 management-title">
<h1>Create New Invoice</h1>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<form>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyID, "CompanyID",new { #Name="CompanyID"})
#Html.DropDownList("CompanyID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.CompanyID , "", new { #class = "text-danger" })
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#bill_to_company">Company Details</a>
</h4>
</div>
<div id="bill_to_company" class="panel-collapse collapse in wrapper-company-details">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyName)
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.CompanyName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyAddress)
#Html.TextAreaFor(model => model.PurchaseInvoiceTable.CompanyAddress, new { #class = "form-control golbal_textarea" })
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.startdate)
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.startdate, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
</div>
</div>
</div>
</div>
</div>
<h2>Product List</h2>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#product_list">Product List</a>
</h4>
</div>
<div id="product_list" class="panel-collapse collapse in input_fields_wrap">
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel panel-default product_wrapper">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#product' + x + '">Product</a>
</h4>
</div>
<div id="product'+x+'" class="panel-collapse collapse in">
<div class="panel-group">
<div class="panel panel-default">
<div class="col-lg-12">
<div class="col-lg-3">
<label>Product</label>
#Html.TextAreaFor(model => model.PurchaseInvoiceDetailsTable.Product)
</div>
<div class="col-lg-6">
<label>Description</label>
#Html.TextAreaFor(model => model.PurchaseInvoiceDetailsTable.ProductDescription)
</div>
'<div class="col-lg-2 form-group">
<label>Price</label>
#Html.TextBoxFor(model => model.PurchaseInvoiceDetailsTable.Price)
</div>
</div>
</div>
</div>
</div>
cancel
</div>
</div>
</div>
</div>
</div>
</div>
<button class="add_field_button btn btn-primary pull-right">Add More Fields</button>
<div class="wrapper-company-details">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Remark)
#Html.TextAreaFor(model => model.PurchaseInvoiceTable.Remark, new { #class = "form-control", #style = "resize:none;" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Remark, "", new { #class = "text-danger" })
</div>
<h1>Payment Term Area</h1>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#payment_term_collapse">Payment Term</a>
</h4>
</div>
<div id="payment_term_collapse" class="payment_term_area panel-collapse collapse in">
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="width:70%;">
<input type="text" class="form-control" id="payment_term" placeholder="Type how many terms client want" />
</th>
<th style="width:30%;">
<button class="btn btn-default" id="add_payment_terms">Add</button>
</th>
</tr>
</table>
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="width:70%;">
Payment Term
</th>
<th style="width:30%;">
Amount
</th>
</tr>
<tr style="background-color:black; color:white;">
<th style="text-align:right;">
Discount
</th>
<th>
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Discount, new { #class = "form-control discount price_textbox", #id = "discount", #Value = "0" })
</th>
</tr>
<tr style="background-color:black; color:white;">
<th style="text-align:right;">
Total
</th>
<th>
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Subtotal, new { #class = "form-control price_textbox total", #id = "totval", #Value = "0" })
</th>
</tr>
</table>
<div id="payment_term_area">
<h2>Payment Terms</h2>
<div class="payment_term_wrapper" style="padding:0; margin:0;">
<table class="table table-bordered" style="width:95%;">
<tr style="background-color:black; color:white;" class="payment_term_wrapper">
<th style="width:70%;">
<input class="pull-right payment_terms_label_input" style="background-color:black; color:white;"></input>
</th>
<th style="width:30%;">
#Html.TextBoxFor(model => model.PaymentTerm.Amount)
</th>
</tr>
X
</table>
</div>
</div>
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="text-align:right; width:70%;">
Last Payment
</th>
<th style="width:30%;">
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Total, new { #class = "form-control price_textbox", #id = "lastpayment", #Value = "0" })
</th>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="col-lg-12">
</div>
<div class="col-lg-12">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Category, "Category")
#Html.DropDownList("Category", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Category, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Method)
#Html.DropDownListFor(model => model.PurchaseInvoiceTable.Method, new List<SelectListItem>
{
new SelectListItem() {Text = "Cash", Value="Cash"},
new SelectListItem() {Text = "Cheque", Value="Cheque"},
new SelectListItem() {Text = "Bank Transfer", Value="BankTransfer"}
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Method, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.PaymentTerm, "PaymentTerm", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.PurchaseInvoiceTable.PaymentTerm, new List<SelectListItem>
{
new SelectListItem() {Text = "1", Value="1"},
new SelectListItem() {Text = "2", Value="2"},
new SelectListItem() {Text = "3", Value="3"}
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.PaymentTerm, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.Status, new { #class = "form-control", #Value = "Active" })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.Status, new { #class = "form-control", #Value = "Active" })
#Html.HiddenFor(model => model.PaymentTerm.Status, new { #class = "form-control", #Value = "Active" })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PaymentTerm.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PaymentTerm.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PaymentTerm.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PaymentTerm.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
</div>
<div class="form-group">
<div>
<input type="submit" value="Create" class="btn btn-primary pull-right" />
#Html.ActionLink("Back", "Index", null, new { #class = "btn btn-small btn-danger pull-right", #style = "margin-right:2%;" })
</div>
</div>
</div>
</form>
}
</div>
</div>
here is my controller
public ActionResult Create()
{
ViewBag.CompanyID = new SelectList(db.SupplierTables, "SupplierID", "SupplierID");
ViewBag.Product = new SelectList(db.ProductTables, "ProductID", "ProductID");
ViewBag.Category = new SelectList(db.CategoryTables, "CategoryID", "CategoryID");
ViewBag.PaymentTerm = new SelectList(db.PaymentTerms, "TermID", "TermID");
return View();
}
[HttpPost]
public ActionResult Create([Bind(Include = "PurchaseInvoiceTable,PurchaseInvoiceDetailsTable,PaymentTerm")]InvoiceWrapper model)
{
if (ModelState.IsValid)
{
db.PurchaseInvoiceTables.Add(model.PurchaseInvoiceTable);
db.PurchaseInvoiceDetailsTables.Add(model.PurchaseInvoiceDetailsTable);
db.PaymentTerms.Add(model.PaymentTerm);
db.SaveChanges();
//model.PurchaseInvoiceTable.PurchaseInvoiceID = model.PurchaseInvoiceDetailsTable.InvoiceID = model.PaymentTerm.InvoiceID;
return RedirectToAction("Index");
}
ViewBag.CompanyID = new SelectList(db.SupplierTables, "SupplierID", "SupplierID");
ViewBag.Product = new SelectList(db.ProductTables, "ProductID", "ProductID");
ViewBag.Category = new SelectList(db.CategoryTables, "CategoryID", "CategoryID");
ViewBag.PaymentTerm = new SelectList(db.PaymentTerms, "TermID", "TermID");
return View(model);
}
The exception you are getting means that one or more of the entities properties that you are trying to save is not valid. e.g. The column is defined as not null and the property you are trying to save is null.
In order to see the validation errors you can use this:
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}",
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
credits
I need to do a loop in another loop and I get a strange error as if it lacked a closing } and I get a compile error on the page. As against the project compiles . the error message is
CS1513 : } expected.
The source indicates the line of code in 1238 while I was not more than 150 lines of code in the page, really strange . help please
#using (Html.BeginForm("VCreateCommande", "CCommande", new { id = "formretouche" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="control-label col-md-2">Support papier</div>
<div class="col-md-10">
#Html.CheckBoxFor(model => model.Tretouche.Supportpapier, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Tretouche.Supportpapier, "", new { #class = "text-danger" })
</div>
</div>
var i = 1;
foreach (var item in Model.Tformats)
{
var idformat = "idformat" + i;
var idquantite = "qteformat" + i;
var idtxt="qte" + #item.Idformat;
int qteretoucheformat=0;
foreach (var itemretoucheformat in Model.Tretouchesformats)
{
if(itemretoucheformat.IdFormat ==item.Idformat)
{
qteretoucheformat = itemretoucheformat.Quantité;
}
}
<div>
<div class="form-group">
<div class="control-label col-md-2 fltleft">Quantité #item.Format</div>
<div class="col-md-10 fltleft">
#Html.TextBoxFor(model => model.Tretoucheformat.Quantité, new { id = idtxt, Name=idtxt })
#Html.ValidationMessageFor(model => model.Tretoucheformat.Quantité, "", new { #class = "text-danger" })
</div>
</div>
</div>
i = i + 1;
}
<div class="form-group">
<div class="control-label col-md-2">Photo...</div>
<div class="col-md-10">
#Html.TextBoxFor(model => model.Tretouche.fichierphoto, new { type = "file" })
</div>
</div>
<input id="idtyperetouche" name="idtyperetouche" type="text" value="#idtyperetouche" class="hdn" />
<input name="idcommande" type="text" value="#idtyperetouche" class="hdn" />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Ajouter" class="btn btn-default" />
</div>
</div>
}
<table class="table">
<tr>
<th>Papier</th>
<th>Quantite</th>
<th>Type de retouche</th>
<th>Photo</th>
</tr>
#foreach (var item in Model.Tretouches)
{
var prix = 0;
<tr>
<td>
#Html.CheckBox("Papier", item.Supportpapier)
</td>
<td>
#Html.DisplayFor(modelItem => item.Quantite)
</td>
#foreach (var typeretouche in Model.Ttyperetouches)
{
if (item.Idtyperetouche == typeretouche.Idtyperetouche)
{
<td>#typeretouche.Libelle</td>
prix = (typeretouche.Prix * item.Quantite);
}
}
<td>
<img src="#item.SRCphoto" class="">
</td>
<td>
#prix €
</td>
<td>
#Html.ActionLink("Modifier", "Edit", "TRetouches", new { id = item.Idretouche }, null) |
#Html.ActionLink("Supprimer", "Delete", "TRetouches", new { id = item.Idretouche }, null)
</td>
</tr>
}
For Razor views (at least MVC 4 and earlier), unlike for a .cs file, the { needs to be on its own line
foreach (var itemretoucheformat in Model.Tretouchesformats)
{
}
Henk's comment suggests this may have been improved in MVC 5.
This's my code in controller:
EApproveEntities db = new EApproveEntities();
DocumentDAO dataDocument = new DocumentDAO();
DocumentTypeData dataTypeDocument = new DocumentTypeData();
public void CreateDropDownListInDocument()
{
dataTypeDocument.GetDocumentType();
IEnumerable<SelectListItem> listTypeDocument = new SelectList(dataTypeDocument.documentType, "Key", "Value");
IEnumerable<SelectListItem> listPriorityDocument = new SelectList(dataDocument.Priority, "Key", "Value");
IEnumerable<SelectListItem> listStatusDocument = new SelectList(dataDocument.Status, "Key", "Value");
ViewBag.dataTypeDocument = listTypeDocument;
ViewBag.dataPriorityDocument = listPriorityDocument;
ViewBag.dataStatusDocument = listStatusDocument;
}
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult CreateDocument()
{
CreateDropDownListInDocument();
Document document = new Document();
return this.View(document);
//return this.View();
}
[ActionName("CreateDocument")]
[AcceptVerbs(HttpVerbs.Post)]
[Multiple_Button(Name = "Document", Value = "Cancel")]
public ActionResult Cancel()
{
return RedirectToAction("ListDocument");
}
//[ActionName("CreateDocument")]
[AcceptVerbs(HttpVerbs.Post)]
[Multiple_Button(Name = "Document", Value = "Create")]
public ActionResult CreateDocument(Document model,FormCollection formCollection)
{
CreateDropDownListInDocument();
return View(model);
}
This in code in View:
<table class="tablestyle">
<tr>
<td >
<div>
#Html.LabelFor(model => model.NameOfDocument)
</div>
</td>
<td>
#Html.TextBoxFor(model => model.NameOfDocument, new { #class = "input-textbox" })
#*#Html.ValidationMessageFor(model => model.NameOfDocument);*#
</td>
</tr>
<tr>
<td >
<div>
#Html.Label("Status")
</div>
</td>
<td>
#Html.DropDownListFor(model => model.Status,
(IEnumerable<SelectListItem>)#ViewBag.dataStatusDocument, new { #class = "combobox_style" })
</td>
</tr>
<tr>
<td >
<div>
#Html.Label(" Priority")
</div>
</td>
<td>
#Html.DropDownListFor(model => model.Priority,
(IEnumerable<SelectListItem>)#ViewBag.dataPriorityDocument, new { #class = "combobox_style" })
</td>
</tr>
<tr>
<td >
<div>
#Html.Label(" Type of Document")
</div>
</td>
<td>
#Html.DropDownListFor(model => model.DocumentType,
(IEnumerable<SelectListItem>)#ViewBag.dataTypeDocument, new { #class = "combobox_style" })
</td>
</tr>
<tr>
<td >
<div>
#Html.Label("Path forder")
</div>
</td>
<td>
#Html.TextBoxFor(model => model.PathFolder,new {#Type="file"})
#* #Html.ValidationMessageFor(model => model.PathFolder)*#
</td>
</tr>
<tr>
<td>
#Html.Label("Note")
</td>
<td>
#Html.TextAreaFor(model => model.Note, new { #class = "textarea_style" })
#*#Html.ValidationMessageFor(model => model.Note)*#
</td>
</tr>
<tr>
<td>
<div class="style_button">
<input type="submit" class="t_button" value="Create" name="Document"/>
</div>
</td>
<td>
<div class="style_button">
<input type="submit" class="t_button" value="Cancel" name="Document"/>
</div>
</td>
</tr>
</table>
I were close all validate . And i use the model of EntityFramwork. Don't have any validate.
But this's result:
I don't understand why it's check validate when i don't do anything.
Because this's take me some error.
Thanks!