Ihave IEnumerable named (JournalArticleTypes ) the elements inside this IEnumerable will help me to access some records of a table named (articletypes) the condition is that when the foreign key (ArticleTypeId) of any element of IEnumerable is being equal to any Id of any record from the table (articletypes) then i will save the record that have this Id in a new SelectList named (articletypes )...so i will use first IEnumerableto get select list from specifc table(articletypes)...how to do it?
I tried by using this wrong code
[AllowAnonymous]
public JsonResult GetArticleType(int journalid)
{
var JournalArticleTypes = _context.JournalArticleTypes.Where(u => u.JournalId == journalid);
foreach(var item in JournalArticleTypes)
{
var articletypes = new SelectList(_context.ArticleTypes.Where(u => u.Id == item.ArticleTypeId), "Id", "Name");
}
return Json(articletypes);
}
Ajax code:
<script>
$("#joartcltypeid").empty();
$(document).ready(function () {
$("#jornlid").change(function () {
$("#joartcltypeid").empty();
$("#joartcltypeid").append($('<option>', { text: "#Localizer["إختر نوع المقالة"]" }));
if ($("#jornlid").val() > 0) {
var JournalOptions = {};
JournalOptions.url = "/#CultureInfo.CurrentCulture.Name/JournalRepositories/GetArticleType/";
JournalOptions.data = { journalid: $("#jornlid").val() };
JournalOptions.success = function (data) {
$.each(data, function (index, row) {
$("#joartcltypeid").append($('<option>', { value: row.value, text: row.text }))
});
};
JournalOptions.error = function () { alert("#Localizer["UniError"]"); };
$.ajax(JournalOptions);
}
});
});
</script>
Related
Hello everyone im just simply trying to load values in a dropdownlist from a controller if I have both the value and text be the same values it works with the model property. But im trying to have the value be the id and the text to be the name with this setup the dropdown is not loading the id.
If both text and value are the same I can just do this and it works
vm.CustomerName = model.CustomerName;
View DDL
#Html.DropDownListFor(e => e.ServiceVM.Employee, Model.Employees, "Select Employee", new { #class = "form-control" })
Some of what i tried.
vm.Employee = new SelectListItem { Value = model.EmployeeID.ToString(), Selected=true };
//vm.EmployeeName = model.EmployeeID.ToString();
//var employee = new Employee_Main();
//try
//{
// employee = context.Employee_Main.Where(z => z.EmployeeID == model.EmployeeID).FirstOrDefault();
//}
//catch(System.Exception) { }
//vm.EmpID = employee.EmployeeID.ToString();
//vm.EmployeeName = employee.EmployeeID.ToString();
I really thought this would of worked.. Im setting the correct 'value' and 'text' that are displayed in the list of ddl items. and also saying selected=true.
//vm.EID = model.EmployeeID;
if (model.EmployeeID != null)
{
if(Int32.TryParse(model.EmployeeID.ToString(), out int empID))
{
var employee = context.Employee_Main.Where(e => e.EmployeeID == empID).FirstOrDefault();
if(employee != null)
{
vm.Employee = new SelectListItem() { Value = employee.EmployeeID.ToString(), Text = employee.EFullName, Selected=true };
}
}
#Html.DropDownListFor(e => e.ServiceVM.Employee, Model.Employees, "Select Employee", new { #class = "form-control" })
I got it working.
I forgot to change my javascript to match with the changing model fields.
var employ = modalA.find(body).find("#ServiceVM_Employee");
//empid.val(jsonObject.employeeid);
//empfn.val(jsonObject.employeefname);
//empln.val(jsonObject.employeelname);
//empem.val(jsonObject.employeeemail);
//emppo.val(jsonObject.employeeposition);
//empname.val(jsonObject.employeefullname);
employ.val(jsonObject.employeeid);
Also for adding content to a listbox.
function displayContactData(conID, modal) {
return $.ajax({
url: '#Url.Action("GetContactInfo", "Service")',
data: { contact: conID },
dataType: 'json',
success: function (data) {
var modalX = modal;
var fullL = modalX.find('.modal-body').find('#lstContact');
fullL.empty();
$.each(data, function () {
fullL.append("<option value='" + this.Value + "'>" + this.Text + "</option");
});
}
});
}
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();
}
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!");
}
});
});
I require some help with my JQuery autocomplete.
Im trying to autocomplete postalcodes filtered by countries but for this I need to send a country value along with the autocomplete term to my mvc controller.
The value of the var country should be send as an extra param towards the controller action but I can't seem to accomplish this.
Here is my setup without the extra param:
View:
#Html.TextBoxFor(j => j.MainAddressCountry, new { data_autocomplete_url = Url.Action("AutoCompletePostalCode", "Location")})
script:
var country = $("#MainAddressCountry");
$('*[data-autocomplete-url]')
.each(function() {
$(this).autocomplete({
source: $(this).data("autocomplete-url"),
messages: {
noResults: '',
results: function() {
}
},
focus: function() {
var menu = $(this).data("uiAutocomplete").menu.element;
var focused = menu.find("li:has(a.ui-state-focus)");
if (menu.parent().hasClass('scroll-wrapper')) {
setTimeout(function() {
var height = menu.parent().height();
if (focused.position().top + focused.height() > height) {
menu.scrollTop(menu.scrollTop() + parseInt(focused.position().top) + focused.height() - height);
}
}, 1);
}
},
"open": function() {
var menu = $(this).data("uiAutocomplete").menu.element;
menu.addClass('scrollbar-dynamic').addClass('autocomplete-scroll');
}
});
}
);
controller:
public ActionResult AutoCompletePostalCode(string term)
{
var items = new[] {"2220", "2222", "1800", "1900", "3541", "5214", "9000", "9002", "9006"};
var filteredItems = items.Where(
item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
);
return Json(filteredItems, JsonRequestBehavior.AllowGet);
}
Anyone that might know how to do the trick?
Thanks in advance.
You need to change the way you build source property into something like this:
source: function(request, response) {
$.getJSON("url here", { parameter1: 'your first parameter', parameter2: 'your second parameter' },
response);
},
Controller action:
public JsonResult Test(string parameter1, string parameter2)
{
//code
}
I have two comboboxes. First comobobox I populate in such way and it works fine:
#Html.DropDownListFor(
x => x.Town,
new SelectList(Model.Towns, "Value", "Text"),
"-- Select town --")
public IEnumerable<SelectListItem> Towns
{
get
{
List<DataRow> TownsListDB = OracleSelect("select * from Towns");
List<SelectListItem> townsItems = new List<SelectListItem>();
foreach (DataRow rw in TownsListDB)
{
townsItems.Add(new SelectListItem { Value = rw[0].ToString(),
Text = rw[1].ToString() });
}
return townsItems;
}
}
And depends on the town, I want to show a list of hospitals:
#Html.DropDownListFor(
x => x.Hospital,
Enumerable.Empty<SelectListItem>(),
"-- Select hospital --")
My jQuery code is:
$('#Town').change(function() {
var selectedTown = $(this).val();
if (selectedTown != null && selectedTown != '') {
$.getJSON('#Url.Action("Hospitals")', { town: selectedTown },
function (hospitals) {
var hospitalsSelect = $('#Hospital');
hospitalsSelect.empty();
$.each(hospitals, function(i, hospital) {
hospitalsSelect.append($('<option/>', {
value: hospital.value,
text: hospital.text
}));
});
});
}
});
and C#:
public ActionResult Hospitals(string town)
{
var modelHospital = new MedicalViewModel();
List<DataRow> HospitalsListDB = modelHospital.OracleSelect
("select * from Hospitals hh where hh.TownID = " + town);
List<SelectListItem> hospitalsItems = new List<SelectListItem>();
foreach (DataRow rw in HospitalsListDB)
{
//example:
//rw[0]=101111
//rw[1]=Dublin
hospitalsItems.Add(new SelectListItem { Value = rw[0].ToString(),
Text = rw[1].ToString() });
}
return Json(
hospitalsItems,
JsonRequestBehavior.AllowGet);
return Json(hospitalsItems, JsonRequestBehavior.AllowGet);
}
But it doesn't work. If I use this code as a Return result, then it's ok:
return Json(Enumerable.Range(1, 6).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
Why combobox doesn't work with my List result from DB?
Use this code :
return Json(hospitalsItems.ToList(), JsonRequestBehavior.AllowGet);
Instead of this in last line
return Json(hospitalsItems, JsonRequestBehavior.AllowGet);
I found out what was the problem. It sounds funny I just needed capital letters in my jQuery code: code select.append($('', { value:hospital.Value, text: hospital.Text }