I have code with 3 search fields. One is a RadioButton and two are DropdownList coming from a database.
I have to search base on above criteria but i will get a wrong result.
public ActionResult Index(string searchby,string did, string sid)
{
ViewBag.did = new SelectList(db.destcities, "Id", "name",did);
ViewBag.sid = new SelectList(db.sourcecities, "Id", "name",sid);
var searches = db.searches.Include(s => s.destcity)
.Include(s => s.sourcecity);
If(!String.IsNullOrEmpty(searchby))
{
searches= db.searches.Where(a => a.type == searchby);
}
if(!String.IsNullOrEmpty(did))
{
int q = int.Parse(did);
searches= db.searches.Where(s => s.destcity.Id == q);
}
if (!String.IsNullOrEmpty(sid))
{
int p = int.Parse(sid);
searches= db.searches.Where(c => c.sourcecity.Id == p);
}
return View(searches);
}
and view code is
#model IEnumerable<Web.Models.search>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>#Html.ActionLink("Create New", "Create") </p>
#using (Html.BeginForm("Index","searches",FormMethod.Get))
{
<label>Trip type</label>
#Html.RadioButton("searchby", "Oneway")<text>Oneway</text>
#Html.RadioButton("searchby", "Roundtrip")<text>Roundtrip</text>
#Html.DropDownList("did", null, htmlAttributes: new { #class = "form-control" })
#Html.DropDownList("sid", null, htmlAttributes: new { #class = "form-control" })
<input type="submit" value="Create" class="btn btn-default" />
}
<table class="table">
<tr>
<th>#Html.DisplayNameFor(model => model.destcity.name)</th>
<th>#Html.DisplayNameFor(model => model.sourcecity.name)</th>
<th>#Html.DisplayNameFor(model => model.vehicle)</th>
<th>#Html.DisplayNameFor(model => model.km)</th>
<th>#Html.DisplayNameFor(model => model.price)</th>
<th>#Html.DisplayNameFor(model => model.type)</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.destcity.name)</td>
<td>#Html.DisplayFor(modelItem => item.sourcecity.name)</td>
<td>#Html.DisplayFor(modelItem => item.vehicle)</td>
<td>#Html.DisplayFor(modelItem => item.km)</td>
<td>#Html.DisplayFor(modelItem => item.price)</td>
<td>#Html.DisplayFor(modelItem => item.type)</td>
<td>#Html.ActionLink("Edit", "Edit", new { id=item.Id })
| #Html.ActionLink("Details", "Details", new { id=item.Id })
| #Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
Related
when we upload file then that uploaded file path or url didnt show on index page and database
[HttpPost]
[ValidateAntiForgeryToken]
[Route("{SocietyURL}/FormMaster/Create")]
public ActionResult Create(FormMaster_IVM objFormMaster, HttpPostedFileBase file)
{
Int32 SocietyID = Int32.Parse(Session["SocietyID"].ToString());
objFormMaster.SocietyID = SocietyID;
FormMasterManager ObjformMasterManager = new FormMasterManager();
ObjformMasterManager.CreateFormMaster(objFormMaster);
ObjformMasterManager = null;
try
{
if (file.ContentLength > 0)
{
string FileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("~/Uploads/"), FileName);
file.SaveAs(path);
}
ViewBag.Message = "File Uploaded Successfully!!";
return View();
}
catch
{
ViewBag.Message = "File upload failed!!";
return View();
}
return RedirectToAction("Index");
}
Here is my view
#using (Html.BeginForm("Create","FormMaster",FormMethod.Post,new { #enctype="multipart/form-data"}))
{
#Html.AntiForgeryToken()
<div class="form-row">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group col-md-12">
#Html.LabelFor(model => model.FormName, "Form Name", htmlAttributes: new { #class = "control-label" })
#Html.ValidationMessageFor(model => model.FormName, "", new { #class = "text-danger" })
#Html.EditorFor(model => model.FormName, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => model.FormDescription, "Form Description", htmlAttributes: new { #class = "control-label" })
#Html.ValidationMessageFor(model => model.FormDescription, "", new { #class = "text-danger" })
#Html.EditorFor(model => model.FormDescription, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => model.DocumentAttachment, "Document Attachment", htmlAttributes: new { #class = "control-label", })
<br />
<input type="file" name="file" required />
</div>
<div class="form-group col-md-12">
<input type="submit" value="Save" class="btn btn-theme1" />
</div>
</div>
}
I wish to save an id field called AssetAssignmentID the value of "2" everytime a new modelname is saved.
I was looking to see if i could do the following;
That was if the Modelname was not null, then save both the ModelName and AssetAssignmentID to = "2"
public ActionResult Create(ClinicalAsset clinicalAssets)
{
try
{
if (ModelState.IsValid)
{
if (clinicalAssets.ModelName != null)
{
clinicalAssets.ModelName = clinicalAssets.ModelName;
clinicalAssets.AssetAssignmentID = "2";
}
db.ClinicalAssets.Add(clinicalAssets);
db.SaveChanges();
return RedirectToAction("Details", "ClinicalAssets", new { ClinicalAssetID = clinicalAssets.ClinicalAssetID });
}
}
However it complains that an object reference is required for non-static field.
If I make reference to the AssetAssignmentID in the ClinicalAsset Model I cannot convert type int to Model.
The populated dropdownlist
private void PopulateModelDropDownList(object selectedModel = null)
{
var ModelsQuery = from d in db.Models.Where(x => x.AssetAssignmentID == 2) orderby d.ModelName select d;
ViewBag.ModelDropDown = new SelectList(ModelsQuery, "ModelID", "ModelName", selectedModel);
}
I would expect that every time a new ModelName is submitted to the database the AssetAssignmentID would always equal the value of two.
edit
I have also tried
var clinicalAsset = new ClinicalAsset { AssetAssignmentID = 2 };
if (clinicalAssets.ModelName != null)
{
clinicalAssets.ModelName = clinicalAssets.ModelName;
}
db.ClinicalAssets.Add(clinicalAsset);
db.SaveChanges();
return RedirectToAction("Details", "ClinicalAssets", new { ClinicalAssetID = clinicalAssets.ClinicalAssetID });
but the error is: Cannot implicitly convert type 'int' to 'Assets.Models.Model'
ClinicalAsset Model:
using Assets.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Assets.Areas.Clinical.Models
{
public class ClinicalAsset
{
[Key]
public int ClinicalAssetID { get; set; }
public int AssetTypeID { get; set; }
public int? ProductID { get; set; }
public int? ManufacturerID { get; set; }
public int? ModelID{ get; set; }
public int? SupplierID { get; set; }
[StringLength(100, MinimumLength = 2)]
public string SerialNo { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public DateTime? PurchaseDate { get; set; }
[StringLength(100, MinimumLength = 2)]
public string PoNo { get; set; }
[DisplayFormat(DataFormatString = "{0:c2}", ApplyFormatInEditMode = true)]
public decimal? Costing { get; set; }
public int? TeamID { get; set; }
public int? BudgetCodeID { get; set; }
public int? StaffID { get; set; }
public bool? Filter { get; set; }
public virtual Model ModelName { get; set; }
public virtual Model AssetAssignmentID { get; set; }
public virtual BudgetCode BudgetCodeJoinColumn { get; set; }
public virtual Product ProductName { get; set; }
public virtual AssetType AssetTypeName { get; set; }
public virtual Manufacturer ManufacturerName { get; set; }
public virtual Staff StaffName { get; set; }
public virtual Team TeamName { get; set; }
public virtual Supplier SupplierName { get; set; }
public virtual ICollection<ClinicalPAT> ClinicalPATs { get; set; }
}
}
Models model
namespace Assets.Models
{
public class Model
{
[Key]
public int ModelID { get; set; }
public int AssetAssignmentID { get; set; }
public string ModelName { get; set; }
}
}
Create Form:
#model Assets.Areas.Clinical.Models.ClinicalAsset
<link href="~/Content/bootstrap-timepicker.min.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Create Asset";
ViewBag.Current = "Create Asset";
}
<div class="pageheader">
<h2><i class="fa fa-pencil"></i>Add Clinical Assets</h2>
<div class="breadcrumb-wrapper">
<span class="label">You are here:</span>
<ol class="breadcrumb">
<li>Asset Management System</li>
<li class="active">Clinical Assets / Add Asset</li>
</ol>
</div>
</div>
<div class="contentpanel">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-btns">
−
</div>
<h4 class="panel-title">Create an asset.</h4>
<p>Please fill in the required boxes as a minimum.<text style="color:red;"> * </text> </p>
</div>
#Html.ValidationSummary()
<div class="panel-body">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.AssetTypeID, "Asset Type:", new { #class = "control-label" })
#Html.DropDownListFor(model => model.AssetTypeID, (SelectList)ViewBag.AssetTypeDropDown, "Please Select From The List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.AssetTypeID, "", new { #class = "text-danger" })
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-6">
<div class="form-group">
<label id="lbltipAddProduct">Select Product:</label> <label id="lbltipAddProduct2" style="display:none;">Enter Product:</label>
<label id="hideproductbutton" style="float: right;"><i class="myClass fa fa-edit" id="product"></i></label>
<label id="shownewproductbutton" Style="float: right; display:none;"><i class="glyphicon glyphicon-remove-circle" id="product2"></i></label>
<div id="Product">
#Html.DropDownListFor(model => model.ProductID, (SelectList)ViewBag.ProductDropDown, "Please Select From The List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ProductID, "", new { #class = "text-danger" })
</div>
<div class="js-product" style="display:none;">
#Html.EditorFor(model => model.ProductName.ProductName, new { htmlAttributes = new { #class = "form-control", #placeholder = "Enter Product Name Here", disabled = "disabled" } })
#Html.ValidationMessageFor(model => model.ProductName.ProductName, "", new { #class = "text-danger" })
</div>
</div>
</div><!-- col-sm-6 -->
</div><!-- row -->
<div id="inputs-for-filters1">
<div class="form-group">
#Html.EditorFor(model => model.Filter)
#Html.LabelFor(model => model.Filter, "Filter Required?")
#Html.ValidationMessageFor(model => model.Filter)
</div>
</div>
<div id="inputs-for-filters2">
<div class="form-group">
#Html.EditorFor(model => model.Filter)
#Html.LabelFor(model => model.Filter, "Filter Required?")
#Html.ValidationMessageFor(model => model.Filter)
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label id="lbltipAddManufacturer">Select Manufacturer:</label> <label id="lbltipAddManufacturer2" style="display:none;">Enter Manufacturer:</label>
<label id="hidemanufacturerbutton" style="float: right;"><i class="myClass fa fa-edit" id="manufacturer"></i></label>
<label id="shownewmanufacturerbutton" Style="float: right; display:none;"><i class="glyphicon glyphicon-remove-circle" id="manufacturer2"></i></label>
<div id="Manufacturer">
#Html.DropDownListFor(model => model.ManufacturerID, (SelectList)ViewBag.ManufacturerDropDown, "Please Select From The List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ManufacturerID, "", new { #class = "text-danger" })
</div>
<div class="js-manufacturer" style="display:none;">
#Html.EditorFor(model => model.ManufacturerName.ManufacturerName, new { htmlAttributes = new { #class = "form-control", #placeholder = "Enter Name Here", disabled = "disabled" } })
#Html.ValidationMessageFor(model => model.ManufacturerName.ManufacturerName, "", new { #class = "text-danger" })
</div>
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-6">
<div class="form-group">
<label id="lbltipAddModel">Select Model:</label> <label id="lbltipAddModel2" style="display:none;">Enter Model Type:</label>
<label id="hidemodelbutton" style="float: right;"><i class="myClass fa fa-edit" id="model"></i></label>
<label id="shownewmodelbutton" Style="float: right; display:none;"><i class="glyphicon glyphicon-remove-circle" id="model2"></i></label>
<div id="Model">
#Html.DropDownListFor(model => model.ModelID, (SelectList)ViewBag.ModelDropDown, "Please Select From The List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ModelID, "", new { #class = "text-danger" })
</div>
<div class="js-model" style="display:none;">
#Html.EditorFor(model => model.ModelName.ModelName, new { htmlAttributes = new { #class = "form-control", #placeholder = "Enter Name Here", disabled = "disabled" } })
#Html.ValidationMessageFor(model => model.ModelName.ModelName, "", new { #class = "text-danger" })
</div>
</div>
</div><!-- col-sm-6 -->
</div><!-- row -->
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label id="lbltipAddSupplier">Select Supplier:</label> <label id="lbltipAddSupplier2" style="display:none;">Enter Supplier:</label>
<label id="hidesupplierbutton" style="float: right;"><i class="myClass fa fa-edit" id="supplier"></i></label>
<label id="shownewsupplierbutton" Style="float: right; display:none;"><i class="glyphicon glyphicon-remove-circle" id="supplier2"></i></label>
<div id="Supplier">
#Html.DropDownListFor(model => model.SupplierID, (SelectList)ViewBag.SupplierDropDown, "Please Select From The List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SupplierID, "", new { #class = "text-danger" })
</div>
<div class="js-supplier" style="display:none;">
#Html.EditorFor(model => model.SupplierName.SupplierName, new { htmlAttributes = new { #class = "form-control", #placeholder = "Enter Supplier Name Here", disabled = "disabled" } })
#Html.ValidationMessageFor(model => model.SupplierName.SupplierName, "", new { #class = "text-danger" })
</div>
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.SerialNo, "Serial No:", new { #class = "control-label" })
#Html.EditorFor(model => model.SerialNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SerialNo, "", new { #class = "text-danger" })
</div>
</div><!-- col-sm-6 -->
</div><!-- row -->
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseDate, "Purchase Date:", new { #class = "control-label" })
#Html.TextBoxFor(m => m.PurchaseDate, new { #class = "form-control datepicker", autocomplete = "off" })
#Html.ValidationMessageFor(model => model.PurchaseDate, "", new { #class = "text-danger" })
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.PoNo, "Purchase OrderNo:", new { #class = "control-label" })
#Html.EditorFor(model => model.PoNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PoNo, "", new { #class = "text-danger" })
</div>
</div><!-- col-sm-6 -->
</div><!-- row -->
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.BudgetCodeID, "Budget Code:", new { #class = "control-label" })
#Html.DropDownListFor(m => m.BudgetCodeID, (SelectList)ViewBag.BudgetsList, "Please Select From The List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BudgetCodeID, "", new { #class = "text-danger" })
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.Costing, "Cost:", new { #class = "control-label" })
#Html.EditorFor(model => model.Costing, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Costing, "", new { #class = "text-danger" })
</div>
</div><!-- col-sm-6 -->
</div><!-- row -->
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.TeamID, "Team:", new { #class = "control-label" })
#Html.DropDownListFor(model => model.TeamID, ViewBag.TeamList as SelectList, "Please Select From The List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TeamID, "", new { #class = "text-danger" })
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-6">
<div class="form-group">
<label id="lbltipAddStaff">Select Staff Member:</label> <label id="lbltipAddStaff2" style="display:none;">Enter Staff Member Name:</label>
<label id="hidestaffbutton" Style="float: right;"><i class="myClass fa fa-edit" id="staff"></i></label>
<label id="shownewstaffbutton" Style="float: right; display:none;"><i class="glyphicon glyphicon-remove-circle" id="staff2"></i></label>
<div id="Staff">
#Html.DropDownListFor(model => model.StaffID, (SelectList)ViewBag.StaffDropDown, "Please Select From The List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StaffID, "", new { #class = "text-danger" })
</div>
<div class="js-staff" style="display:none;">
#Html.EditorFor(model => model.StaffName.StaffName, new { htmlAttributes = new { #class = "form-control", #placeholder = "Enter Name Here", disabled = "disabled" } })
#Html.ValidationMessageFor(model => model.StaffName.StaffName, "", new { #class = "text-danger" })
</div>
</div>
</div><!-- col-sm-6 -->
</div><!-- row -->
</div><!-- panel-body -->
<div class="panel-footer">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
}
</div><!-- panel -->
#section Scripts {
<script src="~/Scripts/jquery-ui-1.10.3.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#Scripts.Render("~/bundles/jqueryval")
<script>
// Date Picker
jQuery('#PurchaseDate').datepicker({ dateFormat: 'dd/mm/yy' });
jQuery('#WarrantyEndDate').datepicker({ dateFormat: 'dd/mm/yy' });
jQuery('#InspectionDate').datepicker({ dateFormat: 'dd/mm/yy' });
jQuery('#InspectionDueDate').datepicker({ dateFormat: 'dd/mm/yy' });
jQuery('#datepicker-inline').datepicker();
jQuery('#datepicker-multiple').datepicker({
numberOfMonths: 3,
showButtonPanel: true
});
$(document).ready(function () {
$("#inputs-for-filters1").hide();
$("#inputs-for-filters2").hide();
$("#AssetTypeID").change(function () {
if ($("#AssetTypeID").val() == "3") {
$("#inputs-for-filters1").show();
}
else {
$("#inputs-for-filters1").hide();
}
});
$("#ProductID").change(function () {
if ($("#ProductID").val() == "24") {
$("#inputs-for-filters2").show();
}
else {
$("#inputs-for-filters2").hide();
}
});
});
$(document).ready(function () {
$("#staff").click(function () {
$("#Staff").toggle();
$(".js-staff").toggle();
$('#lbltipAddStaff').toggle();
$('#lbltipAddStaff2').toggle();
$(".js-staff input[type='text']").attr("disabled", false);
$("#hidestaffbutton").toggle();
$("#shownewstaffbutton").toggle();
});
});
$(document).ready(function () {
$("#staff2").click(function () {
$("#Staff").toggle();
$(".js-staff").toggle();
$('#lbltipAddStaff').toggle();
$('#lbltipAddStaff2').toggle();
$(".js-staff input[type='text']").attr("disabled", true);
$("#hidestaffbutton").toggle();
$("#shownewstaffbutton").toggle();
});
});
$(document).ready(function () {
$("#model").click(function () {
$("#Model").toggle();
$(".js-model").toggle();
$('#lbltipAddModel').toggle();
$('#lbltipAddModel2').toggle();
$(".js-model input[type='text']").attr("disabled", false);
$("#hidemodelbutton").toggle();
$("#shownewmodelbutton").toggle();
});
});
$(document).ready(function () {
$("#model2").click(function () {
$("#Model").toggle();
$(".js-model").toggle();
$('#lbltipAddModel').toggle();
$('#lbltipAddModel2').toggle();
$(".js-model input[type='text']").attr("disabled", true);
$("#hidemodelbutton").toggle();
$("#shownewmodelbutton").toggle();
});
});
$(document).ready(function () {
$("#manufacturer").click(function () {
$("#Manufacturer").toggle();
$(".js-manufacturer").toggle();
$('#lbltipAddManufacturer').toggle();
$('#lbltipAddManufacturer2').toggle();
$(".js-manufacturer input[type='text']").attr("disabled", false);
$("#hidemanufacturerbutton").toggle();
$("#shownewmanufacturerbutton").toggle();
});
});
$(document).ready(function () {
$("#manufacturer2").click(function () {
$("#Manufacturer").toggle();
$(".js-manufacturer").toggle();
$('#lbltipAddManufacturer').toggle();
$('#lbltipAddManufacturer2').toggle();
$(".js-manufacturer input[type='text']").attr("disabled", true);
$("#hidemanufacturerbutton").toggle();
$("#shownewmanufacturerbutton").toggle();
});
});
$(document).ready(function () {
$("#product").click(function () {
$("#Product").toggle();
$(".js-product").toggle();
$('#lbltipAddProduct').toggle();
$('#lbltipAddProduct2').toggle();
$(".js-product input[type='text']").attr("disabled", false);
$("#hideproductbutton").toggle();
$("#shownewproductbutton").toggle();
});
});
$(document).ready(function () {
$("#product2").click(function () {
$("#Product").toggle();
$(".js-product").toggle();
$('#lbltipAddProduct').toggle();
$('#lbltipAddProduct2').toggle();
$(".js-product input[type='text']").attr("disabled", true);
$("#hideproductbutton").toggle();
$("#shownewproductbutton").toggle();
});
});
$(document).ready(function () {
$("#supplier").click(function () {
$("#Supplier").toggle();
$(".js-supplier").toggle();
$('#lbltipAddSupplier').toggle();
$('#lbltipAddSupplier2').toggle();
$(".js-supplier input[type='text']").attr("disabled", false);
$("#hidesupplierbutton").toggle();
$("#shownewsupplierbutton").toggle();
});
});
$(document).ready(function () {
$("#supplier2").click(function () {
$("#Supplier").toggle();
$(".js-supplier").toggle();
$('#lbltipAddSupplier').toggle();
$('#lbltipAddSupplier2').toggle();
$(".js-supplier input[type='text']").attr("disabled", true);
$("#hidesupplierbutton").toggle();
$("#shownewsupplierbutton").toggle();
});
});
</script>
}
UPDATE
I now have the AssignmentID saving as 2, but it creates a new entry in the database rather than assigning two values to the same field
Thanks to A.Nadjar & Train
Although i didn't need a Viewmodel the solution was to save the data with THE 1 TO MANY relationship saving first, followed by the main entity last, and also ensure the foreign key was created for the AssetAssignmentID in the model.
Code:
if (ModelState.IsValid)
{
var newClinicalAsset = new ClinicalAsset();
var NewModel = new Model();
if (clinicalAssetVM.AssetTypeID == 0)
{
}
else
{
newClinicalAsset.AssetTypeID = clinicalAssetVM.AssetTypeID;
}
if (clinicalAssetVM.ModelName != null)
{
NewModel.ModelAssetAssignmentID = clinicalAssetVM.AssetAssignmentID.AssetAssignmentID;
NewModel.ModelName = clinicalAssetVM.ModelName.ModelName;
db.Models.Add(NewModel);
db.SaveChanges();
}
newClinicalAsset = new ClinicalAsset { ModelID = NewModel.ModelID, AssetTypeID = newClinicalAsset.AssetTypeID};
db.ClinicalAssets.Add(newClinicalAsset);
db.SaveChanges();
return RedirectToAction("Details", "ClinicalAssets", new { ClinicalAssetID = clinicalAssetVM.ClinicalAssetID });
}
I have a MatTableDataSource that shows some elements retrieved from my MongoDB and I want to filter each column of the table in order to have only what matches my input.
This is my code:
datatable.component.ts
export class DatatableComponent implements OnInit {
#ViewChild(MatPaginator) paginator: MatPaginator;
pratiche: any;
displayedColumns: string[] = ['idPratica', 'barcode', 'status', 'firstName', 'lastName', 'fiscalCode', 'pratica'];
dataSource = new MatTableDataSource(this.pratiche);
idFilter = new FormControl('');
barcodeFilter = new FormControl('');
filterValues = {
id: '',
barcode: '',
};
constructor(private praticaService: PraticaService) {
this.dataSource.data = this.pratiche;
this.dataSource.filterPredicate = this.createFilter();
}
async ngOnInit() {
const res = await this.praticaService.getAllPratiche();
this.pratiche = res.data;
this.dataSource = new MatTableDataSource(this.pratiche);
this.dataSource.paginator = this.paginator;
this.idFilter.valueChanges
.subscribe(
id => {
this.filterValues.id = id;
this.dataSource.filter = JSON.stringify(this.filterValues);
}
)
this.barcodeFilter.valueChanges
.subscribe(
barcode => {
this.filterValues.barcode = barcode;
this.dataSource.filter = JSON.stringify(this.filterValues);
}
)
}
createFilter(): (data: any, filter: string) => boolean {
let filterFunction = function (data, filter): boolean {
let searchTerms = JSON.parse(filter);
return data.id.toLowerCase().indexOf(searchTerms.id) !== -1
&& data.barcode.toLowerCase().indexOf(searchTerms.barcode) !== -1
&& data.status.toLowerCase().indexOf(searchTerms.status) !== -1
&& data.firstName.toLowerCase().indexOf(searchTerms.firstName) !== -1
&& data.lastName.toLowerCase().indexOf(searchTerms.lastName) !== -1
&& data.fiscalCode.toLowerCase().indexOf(searchTerms.fiscalCode) !== -1;
}
return filterFunction;
}
}
datatable.component.html
<table mat-table [dataSource]="dataSource">
<ng-container matColumnDef="idPratica">
<th class="header" mat-header-cell *matHeaderCellDef>
ID Pratica
<mat-form-field class="filter" floatLabel="never">
<mat-label></mat-label>
<input matInput [formControl]="idFilter">
</mat-form-field>
</th>
<td mat-cell *matCellDef="let element">{{element.id}}</td>
</ng-container>
<ng-container matColumnDef="barcode">
<th class="header" mat-header-cell *matHeaderCellDef>
Barcode
<mat-form-field class="filter" floatLabel="never">
<mat-label></mat-label>
<input matInput [formControl]="barcodeFilter">
</mat-form-field>
</th>
<td mat-cell *matCellDef="let element">{{element.barcode}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let element; columns: displayedColumns;"></tr>
pratica.service.ts
public getAllPratiche(): Promise<any> {
const url = "http://127.0.0.1:3001/pratiche/getPratiche";
return new Promise((resolve, reject) => {
this.http.get(url, { responseType: "json", observe: "response" })
.pipe(map((response: any) => response))
.subscribe(res => {
if (res.error) {
reject(res.error);
} else {
resolve(res.body);
}
}, err => {
reject(err)
});
});
}
I retrieve correctly my data from my MongDb but when I try to filter it, nothing happens. I'm new on angular and probably I am making mistakes on Promise vs Observable. Any suggestion?
I have a business rule of my page - controls with date should be in ascending order. I.e. entered value to Date1 < entered value to Date2 < Date3
My attribute:
public class CompareDateAttribute : ValidationAttribute, IClientValidatable
{
public CompareDateAttribute(string datesString)
{
_datesString = datesString;
}
private string _datesString;
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule()
{
//ErrorMessage = this.FormatErrorMessage(metadata.DisplayName),
ErrorMessage = String.Format("Invalid date {0}", metadata.PropertyName),
ValidationType = "datecomparer"
};
rule.ValidationParameters.Add("dates", _datesString);
yield return rule;
}
}
client side:
$.validator.addMethod("datecomparer", function (value, element, param) {
//var valid = true;
var arrElements = param.split(',');
var datePreviousStr = null;
$.each(arrElements, function (index, v) {
if (datePreviousStr == null)
{
datePreviousStr = $('#' + v).val();
}
else
{
var dateCurrentStr = $('#' + v).val();
if (dateCurrentStr == '')
{
return false;
}
var dateCurrent = $.datepicker.parseDate("mm/dd/yy", dateCurrentStr);
var datePrevious = $.datepicker.parseDate("mm/dd/yy", datePreviousStr);
if (dateCurrent < datePrevious)
{
return false;
}
else
{
datePreviousStr = dateCurrentStr;
}
}
});
return true;
});
$.validator.unobtrusive.adapters.addSingleVal("datecomparer", "dates");
Model:
public class Valid6
{
[CompareDate("Date1,Date2,Date3")]
public DateTime Date1 { get; set; }
[CompareDate("Date1,Date2,Date3")]
public DateTime Date2 { get; set; }
[CompareDate("Date1,Date2,Date3")]
public DateTime Date3 { get; set; }
}
and view (necessary part):
<div class="form-horizontal">
<h4>Valid6</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Date1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date3, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date3, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date3, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
also, part of result HTML:
<input class="form-control text-box single-line valid" data-val="true" data-val-date="The field Date3 must be a date." data-val-datecomparer="Invalid date Date3" data-val-datecomparer-dates="Date1,Date2,Date3" data-val-required="The Date3 field is required." id="Date3" name="Date3" type="datetime" value="">
but when I enter Date1='11/11/2010' and Date2='11/11/2009' debugger says, that datecomparer method returns false, but validator message is not appeared.
Why and how to solve?
Found the solution - "return false;" inside loop returns only from loop and then find "return true" on the end of method.
should be like :
$.validator.addMethod("datecomparer", function (value, element, param) {
var valid = true;
var arrElements = param.split(',');
var datePreviousStr = null;
$.each(arrElements, function (index, v) {
if (datePreviousStr == null)
{
datePreviousStr = $('#' + v).val();
}
else
{
var dateCurrentStr = $('#' + v).val();
if (dateCurrentStr == '')
{
valid = false;
return;
}
var dateCurrent = $.datepicker.parseDate("mm/dd/yy", dateCurrentStr);
var datePrevious = $.datepicker.parseDate("mm/dd/yy", datePreviousStr);
if (dateCurrent < datePrevious)
{
valid = false;
return;
}
else
{
datePreviousStr = dateCurrentStr;
}
}
});
return valid;
});
$.validator.unobtrusive.adapters.addSingleVal("datecomparer", "dates");
I want to add a drop down list to the default Register view in MVC 5 account platform. But I can not do it with View-Models, and can not fill it with proper data. Have anybody some ideas?
public string AddEmployees (RegisterViewModel model)
{
//create user
var user = new ApplicationUser()
{
UserName = model.Email,
Email = model.Email,
UserProfile = new Employees
{
UserProfileId = emphasized text model.UserProfileId,
FirstName = model.FirstName,
LastName = model.LastName,
Gender = gender,
ContactNumber = model.ContactNumber,
Email = model.Email,
PhysicalAddress = model.PhysicalAddress,
IdentityNumber = model.IdentityNumber,
IsFirstTimeLogin = true,
Position = model.Position
}
};
//create user in the aspnet table
var result = UserManager.Create(user, password);
if (result.Succeeded)
{
"Display your Message";
//create role
if (!RoleManager.RoleExists(model.Position))
{
//create a role
}
//assign user to role
UserManager.AddToRole(user.Id, model.Position);
}
return feedback;
}
#model Ingogo.Model.Employee_Management.Model_View.RegisterViewModel
#{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_AdminClerk.cshtml";
}
<h2><span><i class="glyphicon glyphicon-briefcase"></i></span> Add Employee</h2>
#if (ViewBag.Error == "There Is Already An Employee With The Same Information")
{
<p class="alert alert-danger">#ViewBag.Error</p>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Employee First Name", Title = "Example: Prince" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Employee Surname", Title = "Example: Buthelezi" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IdentityNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.IdentityNumber, new { htmlAttributes = new { #class = "form-control", onkeypress = "return isNumberKey(event)", maxlength = "13", #Value = "", placeholder = "Enter South African Identity Number", Title = "Must Be 13 Digits" } })
<script type="text/javascript">
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
#Html.ValidationMessageFor(model => model.IdentityNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Employee Working Email Address", Title = "Example: example#somewhere.com" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PhysicalAddress, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.PhysicalAddress, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PhysicalAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.ContactNumber, new { htmlAttributes = new { #class = "form-control", onkeypress = "return isNumberKey(event)", maxlength = "10", #Value = "0", placeholder = "Enter Employee Cell Number", Title = "Example: 0782115579" } })
<script type="text/javascript">
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
#Html.ValidationMessageFor(model => model.ContactNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Position, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.DropDownListFor(g => g.Position, new SelectListItem[]
{
new SelectListItem {Value = "Farm Manager", Text = "Farm Manager"},
new SelectListItem {Value = "Supervisor", Text = "Supervisor"},
new SelectListItem {Value = "Admin Clerk", Text = "Admin Clerk"},
new SelectListItem {Value = "Farm Assistance", Text = "Farm Manager Assistance"}
}, "--Select Employee type--", new { #class = "form-control", title = "The employee could be of the listed job titles" })
#Html.ValidationMessageFor(model => model.Position, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Add Employee" class="btn btn-primary" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "GetAllEmployees")
</div>