why ajax say 404 not found on server? - c#

Okey problem is i have ajax call and when any property is null ajax is working correctly but when all properties okey ajax say "404 not found".And there is a funny thing that the problem only happens on server.On my localhost there is not any problem.
$(".add-button").click(function (e) {
e.preventDefault();
var id = "#";
var langId = $(".select-language").val();
id += langId;
var realpartno = $(id+" .input-tags").val();
var value = [];
var newRealPart ="";
for (var i = 0; i < realpartno.length; i++) {
if (realpartno[i] != ",") {
newRealPart += realpartno[i];
}
else {
value.push(newRealPart);
newRealPart = "";
}
if (i == realpartno.length - 1) {
value.push(newRealPart);
}
}
var formData = new FormData();
formData.append("Description", $(id + " .description").val());
formData.append("SubCategory", $(id + " .subcategory").val());
formData.append("RealPartNos", value);
formData.append("Categories", $(id +" .category").val());
formData.append("Photo", $(id + " .product_photo").get(0).files[0]);
formData.append("LanguageId", $(".select-language").val());
$(id + " .error_view").empty();
$(id + " .error_view").text("Zehmet Olmasa Gozleyin Sorgu Icra Edilir ...")
$.ajax({
url: "/Admin/Home/Add/",
type: "post",
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
if (response.status == 200) {
swal({
title:"Success",
icon: "success",
text: response.message,
buttons: ["Siyahiya Kec", "Yeni Mehsul Elave Et"]
});
ClearArea("#description");
ClearArea("#product_photo");
ClearElement(".input-tags .item");
var a = document.createElement("a");
a.href = "/Admin/Home/Index";
a.innerText = "Siyahiya Qayit";
a.className = "btn btn-success my-2";
a.style.color = "#fff";
$(id + " .error_view").empty();
$(id + " .error_view").append(a);
} else {
swal({
title: "Error",
icon: "error",
text: response.errorMessage
});
}
}
});
})
Why there is not any problem on my localhost and only problem on server when everyrthing okey.and that is my action
[HttpPost]
public async Task<JsonResult> Add(ProductViewModel model)
{
//Check All Models
foreach (string item in model.Categories)
{
if (item == null)
{
return Json(new { status = 400, errorMessage = "En azi 1 category elave edin" });
}
}
if (model.Description == "")
{
return Json(new { status = 400, errorMessage = "Description elave edin" });
}
if (model.SubCategory == "")
{
return Json(new { status = 400, errorMessage = "En azi 1 Subcategory elave edin" });
}
if (model.Photo == null)
{
return Json(new { status = 400, errorMessage = "Sekil elave edin" });
}
foreach (string item in model.RealPartNos)
{
if (item == null)
{
return Json(new { status = 400, errorMessage = "En azi 1 realpartno elave edin" });
}
}
if (model.LanguageId == "")
{
return Json(new { status = 400, errorMessage = "Dil elave edile bilmir" });
}
//Find Language
Language language = db.Languages.Where(l => l.Key == model.LanguageId).FirstOrDefault();
var sub = model.SubCategory;
var description = model.Description;
//Make Category and RealPartNo Arrays
List<string> categories = MakeArray(model.Categories);
List<string> realPartNos = MakeArray(model.RealPartNos);
//Upload Photo
var photo = model.Photo;
var file_name = photo.FileName;
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Uploads", "Products", file_name);
if (MyFile.isImage(photo))
{
await MyFile.Upload(photo, path);
}
//Create Product
Product product = new Product();
product.SubCategory = await db.SubCategories.Where(s => s.Name == sub).FirstOrDefaultAsync();
product.PhotoPath = photo.FileName;
//Creat RealPartNo
foreach (var realPartNo in realPartNos)
{
RealPartNo number = new RealPartNo();
number.Name = realPartNo;
number.Product = product;
await db.RealPartNos.AddAsync(number);
}
//Create Category
foreach (var item in categories)
{
if (item != null)
{
Category category = await db.Categories.Where(c => c.Name == item).FirstOrDefaultAsync();
ProductCategory productCategory = new ProductCategory();
productCategory.Category = category;
productCategory.Product = product;
db.ProductCategories.Add(productCategory);
}
}
//Create MultiLanguage Product
ProductLanguage productLanguage = new ProductLanguage();
productLanguage.LanguageId = language.Id;
productLanguage.Product = product;
productLanguage.Description = model.Description;
await db.ProductLanguages.AddAsync(productLanguage);
await db.Products.AddAsync(product);
await db.SaveChangesAsync();
return Json(new { status = 200, message = "Mehsul Elave Edildi" });
}

Related

How to populate <select> using ajax in asp.net core mvc

I want to populate #2 by using onchange event of #1 and using ajax to call action in controller but it returns 'undefined'.
I tried JsonResultBehavior.AllowGet but it is deprecated in asp.net core
VIEW:
<div class="col-md-4" style="padding-bottom: 1em;">
<label for="ddlCorporateName">Corporate Name
</label>
<select id="ddlCorporateName" class="form-control" required></select>
</div>
AJAX/jquery:
<script type = "text/javascript">
function GetSelectedStatus(ddlStatus) {
var id = ddlStatus.options[ddlStatus.selectedIndex].innerHTML;
var selectedValue = ddlStatus.value;
//window.location.href = '#Url.Action("PopulateCorporateName",
"POMultipleApprovalSummary") / ' + id;
$(function() {
var ddlCorporateName = $("#ddlCorporateName");
ddlCorporateName.empty().append('<option selected="selected"
value = "0"
disabled = "disabled" > Loading..... < /option>');
$.ajax({
type: "POST",
url: '#Url.Action("PopulateCorporateName", "POMultipleApprovalSummary") / ' + id,
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(reponse) {
ddlCorporateName.empty().append('<option
selected = "selected"
value = "0" > Select All < /option>');
$.each(reponse, function() {
ddlCorporateName.append('<option selected="selected"
value = "' + this.CorporateName + '" > ' + this.CorporateName + '</option>');
});
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
});
}
</script>
CONTROLLER:
[HttpPost][Produces("application/json")]
public JsonResult PopulateCorporateName(string id) {
IPage page = new IPage(_accessor);
string status = id;
string accesslevel = string.Empty;
string CustName = string.Empty;
if (page.UserPageAccessLevel == Models.Constant.UserAccessLevel.BUHead) {
if (status == "Printed") {
accesslevel = "BU01PRINT";
} else if (status == "Pending SAM") {
accesslevel = "BU01";
} else if (status == "Pending Approval") {
accesslevel = "BU01PENDINGAPPROVAL";
} else if (status == "Approved SAM") {
accesslevel = "APPROVEDSAM";
} else if (status == "Rejected SAM") {
accesslevel = "REJECTEDSAM";
}
} else {
if (page.UserPageAccessLevel == Models.Constant.UserAccessLevel.ApproverLevel3) {
accesslevel = "AP03";
} else if (page.UserPageAccessLevel == Models.Constant.UserAccessLevel.ApproverLevel4) {
accesslevel = "AP04";
} else if (page.UserPageAccessLevel == Models.Constant.UserAccessLevel.ApproverLevel2) {
accesslevel = "AP02";
} else if (page.UserPageAccessLevel == Models.Constant.UserAccessLevel.ApproverLevel5) {
accesslevel = "AP05";
}
if (status == "All Pending") {
accesslevel = accesslevel + "ALL";
} else if (status == "Pending Approval") {} else if (status == "Rejected SAM") {
accesslevel = "REJECTEDSAM";
} else if (status == "Approved SAM") {
accesslevel = "APPROVEDSAM";
}
}
try {
List < Models.POMultipleApprovalOverride > items2 = new
List < Models.POMultipleApprovalOverride > ();
Hashtable htParameters2 = new Hashtable();
htParameters2.Add("POMultipleGroup", "");
htParameters2.Add("AccessLevel", accesslevel);
htParameters2.Add("PONumber", "");
htParameters2.Add("CorporateName", "Select All");
items2 = (List < Models.POMultipleApprovalOverride > ) BusinessRules.Corporates.itemPOAppMultiple(htParameters2);
return Json(items2);
} catch(Exception e) {
return Json(e.Message);
}
}
I just wan to populate "CorporateName" element from the Items2 object.
This should work
$.each(reponse, function(index, corpInfo) {
ddlCorporateName.append('<option selected="selected"
value = "' + corpInfo.CorporateName + '" > ' + corpInfo.CorporateName + '</option>');
});
Hope this helps...

Everytime I press a button the website lags even more?(SignalR,Ajax,SQLconenction)

So, i made a dashboard that uses ajax,sqlconnection to sqlserver 2008 and SignalR for realtime data.
Here is an example of the ajax i made that is in a javascript method which is called by the button:
$.ajax({
url: '../api/values',
type: 'GET',
datatype: 'json',
success: function (data) {
var totalLabel = [];
var totalValue = [];
var totalLabel2 = [];
var totalValue2 = [];
var cityValue = [];
var cityValue2 = [];
var cityName = [];
var numIndex = [];
var barColor = "";
var cityString = "";
for (var j = 1; j < cityList.length; j++)
{
cityString = cityString + "||" + " data[i].Names==\"" + cityList[j] + "\"";
}
cityString = "data[i].Names==\"" + cityList[0] + "\""+cityString;
for (var i = 0; i < data.length; i++) {
totalLabel.push(data[i].Names);
totalValue.push(data[i].ValuesDouble);
totalLabel2.push(data[i].Names2);
totalValue2.push(data[i].ValuesDouble2);
//alert(cityString);
if (eval(cityString)) {
numIndex.push(i);
}
}
for (var k = 0; k < numIndex.length; k++) {
cityValue.push(data[numIndex[k]].ValuesDouble);
cityValue2.push(data[numIndex[k]].ValuesDouble2);
cityName.push(data[numIndex[k]].Names);
}
if (numIndex.length > 0) {
for (var h = 0; h < numIndex.length - 1; h++) {
barColor = barColor + "{y:" + cityValue2[h] + ",color:'" + setGraphColor(cityValue2[h], cityValue[h]) + "'}" + ",";
}
barColor = "[" + barColor + "{y:" + cityValue2[numIndex.length-1] + ",color:'" + setGraphColor(cityValue2[numIndex.length-1],cityValue[numIndex.length-1]) + "'}" + "]";
}
else {
barColor = "[" + barColor + "{y:" + data[numIndex[0]].ValuesDouble2 + ",color:'" + setGraphColor(data[numIndex[0]].ValuesDouble2, data[numIndex[0]].ValuesDouble) + "'}" + "]";
}
$(function () {
Highcharts.chart('container', {
chart: {
type: 'column',
backgroundColor: 'black'
},
tooltip: {
formatter: function () {
var s = '<b>' + this.x + '</b><br/><div>__________________________</div><hr>';
$.each(this.points, function () {
s += '<br/><span style="color:' + this.series.color + '">\u25CF</span><b>' + this.series.name + '</b>: ' + this.y;
});
return s;
},
shared: true
},
title: {
text: ''
},
xAxis: {
categories: cityName,
},
yAxis: {
min: 0,
tickInterval: 500,
title: {
text: ''
}
},
legend: {
verticalAlign: 'top',
reversed: false,
backgroundColor: 'lightgrey'
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: 'Daily Schedule',
data: eval(barColor)
},
{
name: 'Actual Delivery',
data: cityValue,
color: '#33FF66'
},
{
name: '0%-69%',
//data: cityValue,
color: '#FF3366'
},
{
name: '70%-89%',
// data: cityValue,
color: '#FFCC33'
},
{
name: '90%-100%',
// data: cityValue,
color: '#003DF5'
}]
});
});
}
})
and here is the example of my Repository to connect to the SQL Server:
public class LocationInfoRepository
{
public IEnumerable<LocationInfo> GetData()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
connection.Close();
connection.Open();
using (SqlCommand command = new SqlCommand(#"
SELECT ... ", connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
{ connection.Open(); }
using (var reader = command.ExecuteReader())
{
return reader.Cast<IDataRecord>().Select(x => new LocationInfo()
{
Names = x.GetString(2),
Values = Math.Round(x.GetDouble(3), 2).ToString("#,##0.00"),
ValuesDouble = x.GetDouble(3),
Values2 = Math.Round(x.GetDecimal(4), 2).ToString("#,##0.00"),
ValuesDouble2 = x.GetDecimal(4)
}).ToList();
}
/*
using (var reader2 = command.ExecuteReader())
{
reader2.NextResult();
return reader2.Cast<IDataRecord>().Select(x => new LocationInfo()
{
SumVol = x.GetString(0)
}).ToList();
}*/
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
MyHub.Show();
}
}
I dont know why every time i click a button that calls the ajax, the dashboard lags even more.Is it the ajax, or the sqlconnection,or even signalR itself.Please help! Thank you in advance.

query send by jquery.load() function to Controller receiving as list of objects containing null values

My controller return a query in response of a ajax call
return Json(new { success = true, query1 }, JsonRequestBehavior.AllowGet);
I receive the result in success function of ajax call. I need to send this query1 to .load fuction like this:
success: function (response) {
alert("success");
var flag2 = "Query";
$("#worker").load("/Worker/AjaxPage", { Flag: flag2, Result:response.query1 });
},
But i receive the flag and query in my controller but all the objects members contain null data. But Result contain same number of objects as query1 have . But all data is null
controller code:
[AllowAnonymous]
[UserAuthorize(Roles = "1, 3")]
public ActionResult AjaxPage(string sortOrder, string currentFilter, string searchString, string[] Name, string[] WorkerNo, string[] Group, string[] Department, string Status, string StartDate, string EndDate,string Flag,List<WorkerViewModel> Result)
{
if (Flag == "Query")
{
return PartialView("_PartialAjaxPage", Result);
}
if (Flag=="Filter")
{
using (db = new BiaqmEntities())
{
var query = (from w in db.workers
from c in db.BsysCountryLists.Where(c => c.ID == w.CountryID).DefaultIfEmpty()
from f in db.farms.Where(f => f.id == w.farm_id).DefaultIfEmpty()
from comp in db.companies.Where(comp => comp.id == w.company_id).DefaultIfEmpty()
from ig in db.InputGroups.Where(ig => ig.ID == w.InputID).DefaultIfEmpty()
select new WorkerViewModel
{
id = w.id,
Name = w.name,
engName = w.name_eng,
WorkerNumber = w.WorkerNumber,
IDNumber = w.id_card_numder,
DOB = w.birth.Value,
Country = c.SHORT_NAME,
Cell = w.CelPhone,
StartWorkingDate = w.start_date.Value,
Email = w.Email,
EndDate = w.EndDate,
Companyid = comp.id,
Farmid = f.id,
CompanyName = comp.name,
FarmName = f.name,
});
var Namequery = query;
var Workerquery = query;
var Groupquery = query;
var Departmentquery = query;
var Activequery = query;
var Inactivequery = query;
var StartDateQuery = query;
var EndDateQuery = query;
if (StartDate != "")
{
var dates = StartDate.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
var startDate1 = DateTime.Parse(dates[0], CultureInfo.CurrentCulture);
var startDate2 = DateTime.Parse(dates[1], CultureInfo.CurrentCulture);
StartDateQuery = query.Where(w => w.StartWorkingDate >= startDate1 || w.StartWorkingDate <= startDate2);
}
if (EndDate != "")
{
var dates2 = EndDate.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
var EndDate1 = DateTime.Parse(dates2[0], CultureInfo.CurrentCulture);
var EndDate2 = DateTime.Parse(dates2[1], CultureInfo.CurrentCulture);
EndDateQuery = query.Where(w => w.EndDate >= EndDate1 || w.EndDate <= EndDate2);
}
if (Name != null)
{
if (Name.Length > 0)
{
List<string> NameList = new List<string>(Name);
Namequery = query.Where(w=>NameList.Contains(w.Name));
}
}
if (WorkerNo != null)
{
if (WorkerNo.Length > 0)
{
List<string> WorkerNoList = new List<string>(WorkerNo);
Workerquery = query.Where(w => WorkerNoList.Contains(w.WorkerNumber));
}
}
if (Group != null)
{
if (Group.Length > 0)
{
List<string> GroupList = new List<string>(Group);
Groupquery = query.Where(w => GroupList.Contains(w.Group));
}
}
if (Department != null)
{
if (Department.Length > 0)
{
List<string> DepartmentList = new List<string>(Department);
Departmentquery = query.Where(w => DepartmentList.Contains(w.Department));
}
}
if (Status == "Active" || Status == "Inactive")
{
var condition1 = query.Where(j => j.StartWorkingDate == null || j.StartWorkingDate < DateTime.Today);
var condition2 = query.Where(e => e.EndDate == null || e.EndDate > DateTime.Today);
if (Status == "Active")
{
Activequery = condition1.Intersect(condition2);
}
if (Status == "Inactive")
{
Inactivequery = query.Except(condition1.Intersect(condition2));
}
}
if (Status == "Active")
{
query = Activequery;
}
else if (Status== "Inactive")
{
query = Inactivequery;
}
else
{
}
if (Name != null)
{
query = query.Union(Namequery);
}
if (WorkerNo != null)
{
query = query.Union(Workerquery);
}
if (Group != null)
{
query = query.Union(Groupquery);
}
if (Department != null)
{
query = query.Union(Departmentquery);
}
if(StartDate!="")
{
query = query.Union(StartDateQuery);
}
if (EndDate != "")
{
query = query.Union(EndDateQuery);
}
var query1 = query.ToList();
return Json(new { success = true, query1 }, JsonRequestBehavior.AllowGet);
}
}
else
{
//do some thing
}
}
}
script code:
<script type="text/javascript">
$(document).ready(function () {
$('#Refresh').click(function () {
alert("im hit");
var FilterName = [];
//items = '';
$('#FLName option:selected').each(function (i) {
FilterName.push($(this).val());
});
//for (var i = 0; i < FilterName.length; i++) { items += ' ' + FilterName[i] };
//alert(items);
//var FilterName =$("#FLName").val();
var FilterWorkerNo = [];
$('#FLWNo option:selected').each(function (i) {
FilterWorkerNo.push($(this).val());
});
var FilterGroup = [];
$('#FLGroup option:selected').each(function (i) {
FilterGroup.push($(this).val());
});
var FilterDepartment = [];
$('#FLDepartment option:selected').each(function (i) {
FilterDepartment.push($(this).val());
});
var FilterStatus = $("#FLStatus").val();
var FilterStartDate = $("#FLSDate").val();
var FilterEndDate = $("#FLEDate").val();
var flag = "Filter";
$.ajax({
url: "#Url.Action("AjaxPage", "Worker")",
type: 'POST',
traditional: true,
data: JSON.stringify({
sortOrder:"",
currentFilter:"",
searchString:"",
Name: FilterName,
WorkerNo: FilterWorkerNo,
Group: FilterGroup,
Department:FilterDepartment,
Status: FilterStatus,
StartDate: FilterStartDate,
EndDate: FilterEndDate,
Flag:flag
}),
dataType: "text json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success");
var flag2 = "Query";
$("#worker").load("/Worker/AjaxPage", { Flag: flag2, Result: response.query1 });
},
error: function (xhr) {
alert(xhr.responseText);
alert("fail");
}
});
});
});
</script>
In script i changed my object to json.stringyfy
var str = JSON.stringify(response.query1);
$("#worker").load("/Worker/AjaxPage", { Flag: flag2, Result: str });
And in controller i get the Result as string type and use Newtonsoft.Json for deserializing.
For Deserializing help :https://www.codeproject.com/Tips/79435/Deserialize-JSON-with-C
Controller change:
public ActionResult AjaxPage(string sortOrder, string currentFilter, string searchString, string[] Name, string[] WorkerNo, string[] Group, string[] Department, string Status, string StartDate, string EndDate,string Flag,string Result)
{
if (Flag == "Query")
{
if (Result != "")
{
List<WorkerViewModel> Deserialobj = (List<WorkerViewModel>)Newtonsoft.Json.JsonConvert.DeserializeObject(Result, typeof(List<WorkerViewModel>));
return PartialView("_PartialAjaxPage", Deserialobj);
}
}
///////// remaining code
}

How to show an empty dropdownlist when another one isn't selected

I have two dropdownlists both connected to the database, one is called Distritos and the other is called Concelhos, while distritos isnĀ“t selected, concelhos should show empty, when the user selects one of the words of distritos, the Concelhos should show. I want to make it like a state-City relation.
This is what i have in my controller:
public ActionResult getcidades(int? distrito = null)
{
var concelho =
Db.Concelhos.OrderBy(r => r.Nome) as IQueryable<Concelho>;
if (distrito != null)
{
concelho = concelho.Where(t => t.Distritos.Id == distrito);
}
return Json(concelho.Select(r => new { Nome = r.Nome, r.Id }), JsonRequestBehavior.AllowGet);
}
This is what i have in my view:
$("#Distrito").on("change", function() {
var valor = $(this).val();
$.ajax({
type: "get",
url: "#Url.Action("
getcidades ","
PiHelper ")",
data: {
distrito: valor
}
})
.done(function(concelho) {
var dropdown = $("#Concelho");
dropdown.empty().focus();
console.log(concelho, dropdown)
for (var i = 0; i < concelho.length; i++) {
$("<option>")
.attr("value", concelho[i].Id)
.text(concelho[i].Nome)
.appendTo(dropdown);
}
})
})
Try this:
$('#distritos').each(function() {
if ($(this).not(':selected'))
{
$('#concelhos').val(0);
}
});
or
if ($('#distritos :selected').length == 0)
{
$('#concelhos options').remove();
}

MVC5 Controller: Check for duplicate in DB before saving?

On my View I have a button I use to submit a [description] value to my Controller via JSON, which is then used to create a new Table record. For example:
[HttpPost]
public JsonResult createNewStatus(string description)
{
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
//var allErrors = ModelState.Values.SelectMany(x => x.Errors);
try
{
if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description }, JsonRequestBehavior.AllowGet);
}
What I'd like to do now (before saving the Status to the DB) is run a check to see if any other records in the INV_Statuses table have a [description] value matching the one submitted to the function for new creation. If there is a match, I want to return an error/validation? message and alert the user the submitted value already exists and to choose it from the DropDownList on the View.
Can anyone provide an example of how to go about this with LINQ in my MVC Controller?
EDIT: Added my View JS code for submitting the new Status:
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
},
error: function () {
alert("ERROR!");
}
});
});
EDIT2:
Adricadar's suggestion:
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
try
{
var existingStatus = db.INV_Statuses.FirstOrDefault(x => x.status_description.ToUpper() == status.status_description.ToUpper());
var isDuplicateDescription = existingStatus != null;
if (isDuplicateDescription)
{
ModelState.AddModelError("Error", "[" + status.status_description + "] already exists in the database. Please select from the DropDownList.");
}
else if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description }, JsonRequestBehavior.AllowGet);
I added a .ToUpper() in my comparison in Controller, but even though the match with .ToUpper() gets identified, the ModelState.AddModelError() code fires, then the code returns and no error message is issued?
The value (though duplicate) still gets added to the dropdownlist (visually, not in DB) via my current JS code:
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
},
error: function () {
alert("ERROR!");
}
});
});
Check for existing status and set status back as follows:
var existingStatus = db.INV_Statuses.FirstOrDefault(s => s.status_description == description);
if (existingStatus ==null)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
else
{
// set the status back to existing
status = existingStatus;
}
Set an existing flag in your response:
return Json(new { ID = status.Id, Text = status.status_description, AlreadyExists = (existingStatus != null) }, JsonRequestBehavior.AllowGet);
Then in your response JavaScript, simply parse out the returned data:
success: function (resp) {
if (resp.AlreadyExists != true)
{
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
}
else
{
alert(resp.status_description + " already exists");
$("#selectStatus").val(resp.Id);
}
}
You can query the database for a status with an existing description and if exists and an model state error.
Be aware that string comparison is case sensitive.
[HttpPost]
public JsonResult createNewStatus(string description)
{
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
//var allErrors = ModelState.Values.SelectMany(x => x.Errors);
try
{
var existingStatus = db.INV_Statuses.FirstOrDefault(x => x.status_description.ToUpper() == status.status_description.ToUpper());
var isDuplicateDescription = existingStatus != null;
string error = String.Empty;
if (isDuplicateDescription)
{
error = "[" + status.status_description + "] already exists in the database. Please select from the DropDownList.";
}
else if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description, Error = error , IsDuplicate = isDuplicateDescription }, JsonRequestBehavior.AllowGet);
}
In javascript verify if response have IsDuplicate = true if is true you skip the part where you need to add an element in dropdown.
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
if(resp.IsDuplicate)
{
//display error from response
//display resp.Error
} else {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
}
},
error: function () {
alert("ERROR!");
}
});
});

Categories