Dynamic DropDownList in ASP.NET MVC NO ACTION RESULT CREATE() - javascript

I CANNOT CREATE CASCADING DROPDOWN IN ACTIONRESULT CREATE, ONLY IN ACTION RESULT INDEX IT WORKS
THERE GOES THE CODE
CONTROLLER
public class PessoasController : Controller
{
private GestarkContext db = new GestarkContext();
// GET: Pessoas
public ActionResult Index()
{
ViewBag.Gabinetes = new SelectList(db.Gabinetes, "GabineteId", "Nome");
var pessoageral = db.Pessoas.Include(a => a.gabojecto).Include(a => a.nivelojecto);
return View(pessoageral.ToList());
}
[HttpPost]
public JsonResult getDistricts(int gbtID)
{
List<Departamento> DepartamentoList = db.Departamentoes.Where(p => p.GbtId == gbtID).ToList();
return Json(DepartamentoList, JsonRequestBehavior.AllowGet);
}
VIEW INDEX - IT WORKS HERE
<script>
$(function () {
$('#Gabinetes').change(function () {
var gbtID = $(this).val();
$.ajax({
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "getDistricts",
data: "{gbtID:'" + gbtID + "'}",
success: function (data) {
$('#DepartamentoList').empty();
$('#DepartamentoList').append('<option selected="selected" value="">Select Departamento</option>')
$.each(data, function (i, d) {
$('#DepartamentoList').append('<option value=' + d.DircId + '>' + d.Depto + '</option>');
});
},
failure: function (data) {
alert('error occured');
}
});
});
});
</script>
<h2>Lista de Funcioários Registrados</h2>
<br />
<label class="col-md-2 control-label">Gabinete</label>
<div class="col-md-5">
#Html.DropDownList("Gabinetes", null, htmlAttributes: new { #class = "form-control" })
</div>
<div class="form-group">
<label class="col-md-2 control-label">Departamento</label>
<div class="col-md-4">
<select id="DepartamentoList" name="DepartamentoList" class="form-control"></select>
</div>
</div>
<p>
#Html.ActionLink("Visualizar Formulário", "Index", "Principal", null, new { #class = "btn btn-default" }) | #Html.ActionLink("Adicionar Novo", "Create", null, new { #class = "btn btn-primary" }) | #Html.ActionLink("Exportar em Excel", "ExportToExcel", null, new { #class = "btn btn-success" })
</p>
...........
NOW ON VIEW CREATE DOES NOT WORK
I write the code as I do in index, but it doesn't work
I NEED YOUR HELP PLEASE

Related

Passing data to stored procedure in MVC using jquery

I'm new to Jquery. I want to pass data to my SQL database via Ajax.
Inside the Controller:
GetCountry Method Gets list of countries from the database proc
public JsonResult GetCountries()
{
using(var db = GetContxt())
{
var eventCountries = db.Database.SqlQuery<LocationModel>(String.Format("Location.spGetCountries")).ToList();
return new JsonResult { Data = eventCountries, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
And a method that sends data to the database:
[HttpPost]
public JsonResult SavePatient(LocationModel locationModel)
{
string connection = ConfigurationManager.ConnectionStrings["EnrollmentEntity"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
SqlCommand cmd = new SqlCommand("Profile.spAddPatientProfile", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#FirstName", locationModel.FirstName));
cmd.Parameters.Add(new SqlParameter("#LastName", locationModel.LastName));
cmd.Parameters.Add(new SqlParameter("#IDNumber", locationModel.ID_Number));
cmd.Parameters.Add(new SqlParameter("#Line1", locationModel.Line1));
cmd.Parameters.Add(new SqlParameter("#Line2", locationModel.Line2));
cmd.Parameters.Add(new SqlParameter("#CountryIDFK", Int32.Parse(locationModel.CountryIDFK)));
cmd.Parameters.Add(new SqlParameter("#Message", SqlDbType.VarChar, 250)).Direction = ParameterDirection.Output;
try
{
conn.Open();
cmd.ExecuteNonQuery();
locationModel.Message = Convert.ToString(cmd.Parameters["#Message"].Value);
conn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
return new JsonResult { Data = locationModel, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Now this is my Ajax method that i want to send data to my controller method
function SaveButton()
{
$.ajax({
url: "/Home/SavePatient",
type: "POST",
data: $("#frmHome").serialize(),
async: false,
error: function (xhr, status, error)
{
alert("was not successful xhr: " + xhr.value + " status: " + status.value + " error: " + error.value);
},
success: function (Record)
{
alert("was successful");
}
})
}
These are my HTML elements textboxfor and dropdownListfor
#{
ViewBag.Title = "Home Page";
}
#using PatientEnrollmentVS.Models;
#model LocationModel
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
#using (Html.BeginForm("SavePatient", "Home", FormMethod.Post, new { #id = "frmHome" }))
{
<div class="row">
<label>First Name</label>
#Html.TextBoxFor(x => x.FirstName, new { #class = "select-block" })
<label>Last Name</label>
#Html.TextBoxFor(x => x.LastName, new { #class = "select-block" })
</div>
<div class="row">
<label>ID Number</label>
#Html.TextBoxFor(x => x.ID_Number, new {#class = "select-block"})
</div>
<div class="row">
<label>DateOfBirth</label>
#Html.TextBoxFor(x => x.DateOfBirth, new { #class = "select-block" })
</div>
<div class="row">
<label>Countries</label>
#Html.DropDownListFor(x => x.CountryId, new List<SelectListItem>()
{ new SelectListItem()
{
Value = Model.CountryId,
Text = Model.CountryName,
Selected = true
}
}, "0", new { id = "dllGetCountries", #class = "select-block", name = "Countries" })
</div>
<div class="row">
<input type="button" value="Save Event" class="btn btn-primary" onclick="SaveButton()" />
</div>
var valdata = $("#frmHome").serialize();
$.ajax({
url: "/Controller/Method",
type: "POST",
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: valdata
});

Dropdown list return always default value 0

I have problem. When i didn't search something in dropdown It has got default selected value=0. And its saving my database. If it can send value"NULL" not will save in my database. How can i send default value "NULL"?
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-8">
#*#Html.DropDownList("CustomerID", null, new { #class = "form-control", required = "required", placeholder = "Müşteri Seçiniz" })*#
#Html.DropDownList("CustomerID", Enumerable.Empty<SelectListItem>(), "", new { #multiple = "multiple", #id = "CustomerID", #class = "form-control" })
#Html.ValidationMessageFor(model => model.CustomerID, "", new { #class = "text-danger", style="color:red"})
<p style="color:red;margin-bottom:-3px" id="errorpersonel"></p>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
debugger;
$("#CustomerID").pqSelect({
singlePlaceholder: '', width: '92%'
});
$.ajax({
url: "/TicketDashboard/GetCustomer",
method: "Post",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#CustomerID").empty();
$.each(data, function (index, value) {
debugger;
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.CustomerName + '</option>');
});
$("#CustomerID").pqSelect("refreshData");
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez.');
}
});
});
$("#CustomerID").pqSelect({
singlePlaceholder: '',
multiplePlaceholder: 'Müşteri Seçiniz',
maxSelect: 1,
}).on("change", function (evt) {
pccmail = $(this).val();
if (pccmail != "") {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('');
} else {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez');
}
$('[id^=CCMailinput]').val(pccmail);
});
Its my codes. How can i change selected value "0"? It should be "NULL" when i sent form
You can choose a null value as below if the selected value is 0.
pccmail = $(this).val()=="0"?null:(this).val();
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-8">
#*#Html.DropDownList("CustomerID", null, new { #class = "form-control", required = "required", placeholder = "Müşteri Seçiniz" })*#
#Html.DropDownList("CustomerID", Enumerable.Empty<SelectListItem>(), "", new { #multiple = "multiple", #id = "CustomerID", #class = "form-control" })
#Html.ValidationMessageFor(model => model.CustomerID, "", new { #class = "text-danger", style="color:red"})
<p style="color:red;margin-bottom:-3px" id="errorpersonel"></p>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
debugger;
$("#CustomerID").pqSelect({
singlePlaceholder: '', width: '92%'
});
$.ajax({
url: "/TicketDashboard/GetCustomer",
method: "Post",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#CustomerID").empty();
$.each(data, function (index, value) {
debugger;
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.CustomerName + '</option>');
});
$("#CustomerID").pqSelect("refreshData");
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez.');
}
});
});
$("#CustomerID").pqSelect({
singlePlaceholder: '',
multiplePlaceholder: 'Müşteri Seçiniz',
maxSelect: 1,
}).on("change", function (evt) {
pccmail = $(this).val()=="0"?null:(this).val();
if (pccmail != "") {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('');
} else {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez');
}
$('[id^=CCMailinput]').val(pccmail);
});

How can I get my jquery autocomplete to fill in multiple fields in MVC?

I am trying to setup an autocomplete in jquery that gets information from a user in Active Directory. A user can type in a few letters of a person's last name, and what returns is a 2D list (List>) that contains all the people whose last name starts with those letters. Each List holds the first, middle, last name and AD name of a person. And of course, each List> element represents a person.
I have no issues getting the data in jquery. The problem is that I can't seem to figure out how to make it populate the Employee_Name and Employee_Name_AD fields with the information in this array once the user clicks on a name from the list. This is my jquery code:
#section page {
<script type="text/javascript">
$(document).ready(function () {
var name;
var adname;
$("#TESTING").autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Employees/GetUserList",
type: "POST",
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
name = item[0] + " " + item[1] + " " + item[2];
adname = item[3];
return { label: name, data: [name, adname] };
}))
},
select: function (event, ui) {
$('#Employee_Name').val(ui.data.item.data[0]);
$('#Employee_Name_AD').val(ui.data.item.data[1]);
}
})
},
});
})
</script>
}
And on the same page, here is the accommodating Razor code:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-10">
#Html.TextBox("TESTING")
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Name_AD, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Name_AD, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Name_AD, "", 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>
}
I found something super close to what I want thanks to stack overflow: http://jsbin.com/vasuliru/2/edit?html,js,output
The problem with the previous example is that the data is declared on the page itself, not pulled from a data source. How can I modify my code to get it to do what I want?
I was finally about to find a solution, after I came across something in php: Jquery ui autocomplete on multiple input fields with ajax results.
My final code is this:
#section page {
<script type="text/javascript">
$(document).ready(function () {
var name;
var adname;
$("#UserLookup").autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Employees/GetUserList",
type: "POST",
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
name = item[0] + " " + item[1] + " " + item[2];
adname = item[3];
console.log(adname);
return { label: name, data: item }
}));
}
});
},
select: function (event, ui) {
console.log(ui.item);
$(this).val(ui.item.label);
var userid = ui.item.value;
console.log("Here is the userid:");
console.log(item);
console.log(ui.item.data[3]);
$('#Employee_Name').val(ui.item.value);
$('#Employee_Name_AD').val(ui.item.data[3]);
}
});
});
</script>
}

Jquery Ajax call does not call Asp.net mvc controller action method

I have two drop-downs State and City.According to State selected city should be loaded.So I use State drop-down change event to call ajax method to populate City drop-down.
HTML
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>State</label>
#Html.DropDownListFor(m => m.State, Model.States, "Please select a State", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>Cities</label>
#Html.DropDownListFor(m => m.CityRegisterScreen, new SelectList(string.Empty, "Id", "Name"), "Please select a city", new { #class = "form-control" })
</div>
</div>
</div>
JavaScript
This Contains Jquery and Javascript Code.
$(document).ready(function () {
$("#State").on("change", function () { // whenever a selection is made
$("#CityRegisterScreen").empty();
var id = $("#State").val();
$.ajax({
type: 'GET', // we are calling json method
url: '#Url.Action("GetCitiesByDistrict", "Account")',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { id: id },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityRegisterScreen").append('<option value="' + city.value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
return false;
});
});
Controller
This is the controller action method which returns Json
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
Issue is when ajax method is called it doesn't call the Action method in controller.I double checked the URL and DataType it's all perfect.But Action method didn't get called.
It is silly!!! How did i miss this. Thank You #Rajshekar Reddy for your comment it guided me. I am missing [AllowAnonymous] attribute.
[AllowAnonymous]
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
This is a code for loading States according to selected country. Try this solution.
HTML
#Html.DropDownListFor(model => model.CustAddr_Country_ID, Model.Countries, "Select Country", htmlAttributes: new { #class = "disableInput", #id = "ddlstate", #onchange = "javascript:GetCity(this.value);" })
#Html.DropDownListFor(model => model.CustAddr_State_ID, ViewBag.CustAddr_State_ID as SelectList, "Select State", htmlAttributes: new { #class = "disableInput"})
Script
function GetCity(_stateId) {
$("#CustAddr_State_ID").empty().trigger('change');
var newOption = new Option("Select State", 0, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
if (_stateId != null && _stateId != "") {
var url = "/Ajax/GetCityByStaeId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
for (var x = 0; x < data.length; x++) {
var newOption = new Option(data[x].Text, data[x].Value, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
}
$('#CustAddr_State_ID').val('0').trigger('change');
},
error: function (reponse) {
//alert("error : " + reponse);
}
});
}
}
Controller
[HttpPost]
public ActionResult GetCityByStaeId(int stateid)
{
List<State> objcity = new List<State>();
objcity = _state.GetState().Where(m => m.State_Country_ID == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "State_ID", "State_Name", 0);
return Json(obgcity);
}

cascading drop-down list in mvc 4

I created cascading drop-down list as shown in the picture
here the view
here the cshtml code snippet
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.HEI_ID)
#Html.Label("*", new { id="star" , #class = "requiredFiledCol" })
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.HEI_ID, (SelectList)ViewBag.UniversityList_New, "Select University / Institute", new {id="University", #class = "form-control" })
#Html.ValidationMessageFor(model => model.HEI_ID)
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.COL_ID)
#Html.Label("*", new { id="star" , #class = "requiredFiledCol" })
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.COL_ID, (SelectList)ViewBag.FacultyList_New, "Select College", new {id="College", #class = "form-control" })
#Html.ValidationMessageFor(model => model.COL_ID)
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.DEP_ID)
#Html.Label("*", new { id="star" , #class = "requiredFiledCol" })
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.DEP_ID, (SelectList)ViewBag.DepartmentList_New, "Select Department", new { id="Department" , #class = "form-control" })
#Html.ValidationMessageFor(model => model.DEP_ID)
</div>
</div>
This is jquery code snippet
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#University").change(function () {
$("#College").empty();
$("#Department").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetColleges")', // we are calling json method
dataType: 'json',
data: { uni_id: $("#University").val() },
success: function (Colleges) {
$.each(Colleges, function (i, state) {
$("#College").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
$("#College").change(function () {
$("#Department").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetDepartments")', // we are calling json method
dataType: 'json',
data: { col_id: $("#College").val() },
success: function (Departments) {
$.each(Departments, function (i, state) {
$("#Department").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
But in last dropdown (department drop down) its not populate , how can I overcome this
this is the action methods related to this module
public JsonResult GetColleges(string uni_id)
{
var Colleges = from college in db.Colleges
where college.HEI_ID == uni_id & college.Status == true
select college;
//List<SelectListItem> states = new List<SelectListItem>();
return Json(new SelectList(Colleges.ToList(), "College_ID", "College_Name"));
}
public JsonResult GetDepartments(string col_id)
{
var Departments = from department in db.Departments
where department.College_ID == col_id & department.Status == true
select department;
//List<SelectListItem> states = new List<SelectListItem>();
return Json(new SelectList(Departments.ToList(), "Department_ID", "Name_of_Department"));
}
I tried out your code and it is working for me fine but not when you have only one item returned and populated in the College dropdown. That is because change() will not be fired if you have only 1 item and you select that. So to avoid what you can do is when cascade load data in dropdown add a option label so that user has to select a valid option and change gets fired and thus, Department dropdown get loaded with data. So your College change can look like this:
$("#College").change(function () {
$("#Department").empty();
//If option label was selected then do not send request
if ($("#College").val() == 0)
{
return;
}
$.ajax({
type: 'POST',
url: '#Url.Action("GetDepartments")',
dataType: 'json',
data: {
col_id: $("#College").val()
},
success: function (Departments) {
//Add option label as the first element (selected by default)
$("#Department").append('<option value="0">-SELECT COLLEGE-</option>');
$.each(Departments, function (i, state) {
$("#Department").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
});
NOTE: Changes indicated with comment above code

Categories

Resources