Controller Json result
public JsonResult GetStaffJson( string Branch)
{
List<SelectListItem> S_li = new List<SelectListItem>();
try
{
TempData["Staff_List"] =S_li = cmnclass.Get_staff_SelectList(Branch);
}
catch (Exception ex)
{
logger.LogError(ex);
}
finally
{
}
return Json(S_li, JsonRequestBehavior.AllowGet);
}
View
#Html.DropDownListFor(m => m.clsAUDIT.Branch, ViewBag.Branch_list as IEnumerable<SelectListItem>,"Select a Branch", new {#id="ddlBranch", #class = "form-control", #actor = "DropDown" })
And
#Html.DropDownListFor(m=>m.clsCGT.fo_Name_CGT, TempData["Staff_List"] as IEnumerable<SelectListItem> , new {#id="ddl_CGT_fo",#class="input-sm", #actor = "DropDown", #style = "width:auto;" })
Two more
#Html.DropDownListFor(m => m.clsGRT.GRT_fo_Name, TempData["Staff_List"] as IEnumerable<SelectListItem>, new {#id="ddl_GRT_fo", #class = "input-sm", #actor = "DropDown", #style = "width:auto;" })
#Html.DropDownListFor(m => m.clsGRT.GRT_bm_name, TempData["Staff_List"] as IEnumerable<SelectListItem>, new { #id = "ddl_GRT_bm", #class = "input-sm", #actor = "DropDown", #style = "width:auto;" })
Now Jquery
$('#ddlBranch').change(function () {
var url = '#Url.Action("GetStaffJson", "Annex1")';
var Branch = $("#ddlBranch").val();
var ddl_CGT_fo = $("#ddl_CGT_fo");
var ddl_GRT_fo = $("#ddl_GRT_fo");
var ddl_GRT_bm = $("#ddl_GRT_bm");
$.getJSON(url, { Branch: Branch }, function (response) {
ddl_CGT_fo.empty();
ddl_GRT_fo.empty();
ddl_GRT_bm.empty();
debugger;
$.each(response, function (index, item) {
debugger;
var p = new Option(item.Text, item.Value);
ddl_CGT_fo.append(p);
ddl_GRT_fo.append(p);
ddl_GRT_bm.append(p);
});
});
});
On change of ddlBranch I am populating three DropDownList's
ddl_CGT_fo
ddl_GRT_fo
ddl_GRT_bm
Its working fine but only populating last DropDownList ' ddl_GRT_bm' ,
What I am missing here ? why first two DropDownList Still empty ?
You should use the .clone() function for the new created option while appending it.
var p = new Option(item.Text, item.Value);
ddl_CGT_fo.append($(p).clone());
ddl_GRT_fo.append($(p).clone());
ddl_GRT_bm.append($(p).clone());
Related
I have a static dropdownlist and editor need to take the selected value from the dropdownlist and the written value from the editor and make a concatenation between the two values and save it in a Database table column in the post ActionResult:
This is the View:
#Html.DropDownList("Term.Description", new List<SelectListItem>
{
new SelectListItem{ Text="Winter", Value = "Winter-" },
new SelectListItem{ Text="Spring", Value = "Spring-" },
new SelectListItem{ Text="Fall", Value = "Fall-" },
new SelectListItem{ Text="Summer", Value = "Summer-" }
}, new { #class = "description-text" })
#Html.Editor("TermYear","", new { htmlAttributes = new { #class = "description-text", placeholder = "2018", data_placeholder = " " } })
ActionResult:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Term term, int[] applicantTypes)
{
ModelState.Remove("ApplicantTypes");
if (ModelState.IsValid)
{
if (applicantTypes != null && applicantTypes.Length > 0)
{
foreach (var item in applicantTypes)
{
term.ApplicantTypes.Add(db.ApplicantTypes.FirstOrDefault(x => x.ApplicantTypeID == item));
}
}
db.Terms.Add(term);
db.Configuration.ValidateOnSaveEnabled = false;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ApplicantTypes = new MultiSelectList(db.ApplicantTypes, "ApplicantTypeID", "Name", term.ApplicantTypes.Select(x => x.ApplicantTypeID));
return View(term);
}
Finally, I need the `Term.Description = DropDownListSelectedValue-EditorValue'
I feel like I have a working idea but I am getting a "Object reference not set to an instance of an object" error when I build the application. I am simply trying to display a drop down list for cities after the selection for state is made. I have a list of states in a seperate class that I am using for a drop down list in a form. What I am attempting to do is grab the selected state and pass it as a perameter into a different class in order to select the correct list of cities to be displayed as another drop down. So if someone selects washington state then cities such as Seattle and Tacoma show up and not cities from a different state. Here is the razor for the drop downs (the state works fine):
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.State, WebGridProject.Models.StateCodes.GetStatesList(), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.City, WebGridProject.Models.CityNames.GetStateCities(Model.State), new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
And here is the class for cities:
public class CityNames
{
public static IEnumerable<SelectListItem> GetStateCities(string stateName)
{
IList<SelectListItem> cities = new List<SelectListItem>();
switch (stateName)
{
case "AK":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Anchorage", Value = "Anchorage"},
new SelectListItem() {Text = "Fairbanks", Value = "Fairbanks"},
};
break;
case "AL":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Auburn", Value = "Auburn"},
new SelectListItem() {Text = "Birmingham", Value = "Birmingham"},
new SelectListItem() {Text = "Dothan", Value = "Dothan"},
new SelectListItem() {Text = "Mobile", Value = "Mobile"},
};
break;
case "AZ":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Pheonix", Value = "Pheonix"},
new SelectListItem() {Text = "Flagstaff", Value = "Flagstaff"},
new SelectListItem() {Text = "Prescott", Value = "Prescott"},
new SelectListItem() {Text = "Tucson", Value = "Tucson"},
};
break;
case "AR":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Fayetteville", Value = "Fayetteville"},
new SelectListItem() {Text = "Fort smith", Value = "Fort smith"},
new SelectListItem() {Text = "Jonesboro", Value = "Jonesboro"},
new SelectListItem() {Text = "Texarkana", Value = "Texarkana"},
};
break;
default:
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Please Select State", Value = "Please Select State"},
};
break;
}
return cities;
}
}
to me the error seemed to be pointing to there being no default value and having an issue with loading a null value. But I have a default case in the switch statement to cover this issue. I am pretty new to MVC and I will continue to work on this on my own. But if anyone has any ideas I am all ears because I am struggling to figure this out. Just FYI, the states class is also an IList<> that returns the list of state names.
request for action to be posted:
public ActionResult MyHomePage()
{
return View();
}
//Post method
[HttpPost]
public ActionResult MyHomePage(WebGridTable TWG)
{
try
{
if (ModelState.IsValid)
{
UserManager UM = new UserManager();
UM.addNewUser(TWG);
ModelState.Clear();
return View();
}
return View();
}
catch (Exception e)
{
return View("Error");
}
}
action doesnt really mean anything without the method I wrote for managing the form:
public void addNewUser(WebGridTable AddNew)
{
using (WebGridDBEntities4 db = new WebGridDBEntities4())
{
WebGridTable TWG = new WebGridTable();
TWG.Name = AddNew.Name;
TWG.DOB = AddNew.DOB;
TWG.AddressLine1 = AddNew.AddressLine1;
// TO DO: Figure out issue with accepting null value into database.
if (AddNew.AddressLine2 != null)
{
TWG.AddressLine2 = AddNew.AddressLine2;
}
else if (AddNew.AddressLine2 == null)
{
TWG.AddressLine2 = 0;
}
TWG.State = AddNew.State;
TWG.City = TWG.City;
TWG.Zip = AddNew.Zip;
TWG.Gender = AddNew.Gender;
db.WebGridTables.Add(TWG);
db.SaveChanges();
}
}
You need to use JQuery actions on Changes of the States DropDownList. Send the value to a specific Action in your Controller and Call your States.GetStatesName('Value') in that. Check the Code below. I think it would help.
$("#State").on('change',function () {
var loadingoption = $('<option></option>').text("Pleas Wait");
$('#city').attr("disabled","disabled").empty().append(loadingoption);
jQuery.getJSON("/Home/CityJson/" + $("#State > option:selected").attr("value"), function (data) {
var defaultoption = $('<option value="">Please choose a City</option>');
$('#city').removeAttr("disabled").empty().append(defaultoption);
jQuery.each(data, function (i) {
var option2 = $('<option></option>').attr("value", data[i].Name).text(data[i].Name);
$("#city").append(option2);
});
});
});
I used ActionResult "CityJson" in my HomeController. So choose your Action in getJSON.
Here is the Controller:
public ActionResult CityJson(string id)
{
var state = db.States.FirstOrDefault(x => x.Name == id);
var model = db.Cities.Where(x => x.StateId == state.Id).Select(x => new { x.Name }).ToList();
return Json(model, JsonRequestBehavior.AllowGet);
}
you can call your actions inside the Class and send them using Json.
Good Luck.
Hi I have four fields in my view CustomerName, ContactPerson, Email, MobileNo
CustomerName and ContactPerson are Cascading Dropdown, and Email and MobileNo are textboxes.
If I select the CustomerName, related ContactPerson will load automatically in ContactPerson dropdown.
If I select the Contactperson the Contact person related Email and PhoneNo will load automatically in Email and PhoneNo textbox. This works as expected.
Now all are working fine the two cascading drop down are working fine now my issue is if i select the contact person the contact person related Email and phone no is not displaying in that appropriate text boxes.
My Controller Code:
public JsonResult GetCustomers()
{
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetContactPersobByCustomerId(string customerId)
{
Guid Id = Guid.Parse(customerId);
var customercontacts = (from a in db.CustomerContacts where a.CustomerID == Id select a);
return Json(customercontacts, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
var resultMobileNumber = string.Empty;
var resultEmail = string.Empty;
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
if (ContactID != null)
{
var contact = (from p in db.Contacts where p.ContactID == ContactID select p).FirstOrDefault();
if (contact != null)
{
if (string.IsNullOrEmpty(contact.Mobile1) == false)
{
resultMobileNumber = contact.Mobile1;
}
else if (string.IsNullOrEmpty(contact.Mobile2) == false)
{
resultMobileNumber = contact.Mobile2;
}
}
if (contact != null)
{
if (string.IsNullOrEmpty(contact.Email1) == false)
{
resultEmail = contact.Email1;
}
else if (string.IsNullOrEmpty(contact.Email2) == false)
{
resultEmail = contact.Email2;
}
}
}
var details = new { success = true, email = resultEmail, mobileno = resultMobileNumber };
return Json(details, JsonRequestBehavior.AllowGet);
}
View Code:
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerID, new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new { #class = "form-control required", type = "text" })
#Html.Label("Contact Person", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { #class = "form-control", type = "text", id = "CustomerContactID" })
#Html.LabelFor(model => model.MobileNo, new { #class = "control-label" })
#Html.TextBoxFor(model => model.MobileNo, new { #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.MobileNo)
#Html.LabelFor(model => model.Email, new { #class = "control-label" })
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Email)
J-query Code
<script src="~/Scripts/jquery-ui-1.11.0.js"></script>
<script>
$(function () {
$.ajax(
'#Url.Action("GetCustomers", "VisitorsForm")',{
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
$('#CustomerID').change(function () {
$('#CustomerContactID').empty();
$.ajax(
'#Url.Action("GetContactPersobByCustomerId", "VisitorsForm")',{
type: "POST",
datatype: "Json",
data: { CustomerID: $('#CustomerID').val() },
success: function (data) {
$('#CustomerContactID').append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, value) {
$('#CustomerContactID').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
});
}
});
});
});
$("#CustomerContactID").change(function () {
alert("hhh");
debugger;
$.ajax(
'#Url.Action("GetPhoneNoByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "html",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#Email").val(data.email);
$("#MobileNo").val(data.mobileno)
alert("Success");
}
});
});
Now all are working fine when i click the contact person it come to the GetPhoneNoByContactPersonID action it calculate the values and return again to the view ans it is also visible in Network too. All are perfect but it not displaying the data in textbox. while i inspect the code it didn't show any error in console. But it shows one warning message which is mentioned below.
Now all are working fine. But i donno why it is not displaying i donno where is the issue is. I tried my level bwst to explain my issue.-please any one help me to clear this issue.
Advance Thanks
There is no id associated with.So assign an id first in TextBoxFor like this.
#Html.TextBoxFor(model => model.MobileNo, new {#id = "MobileNo", #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.TextBoxFor(model => model.Email, new {#id = "Email", #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
Now this should work
$("#Email").val(data.email);
$("#MobileNo").val(data.mobileno)
I have several textboxes and one dropdownlist like:
for (int i = 0; i < count; i++)
{
<tr>
<td>#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { #id = "ddlProjectvalue" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SUN_HRS, new { style = "width:50px; height:30px;", #class = "sunhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].MON_HRS, new { style = "width:50px; height:30px;", #class = "monhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].TUE_HRS, new { style = "width:50px; height:30px;", #class = "tuehrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].WED_HRS, new { style = "width:50px; height:30px;", #class = "wedhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].THU_HRS, new { style = "width:50px; height:30px;", #class = "thurhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].FRI_HRS, new { style = "width:50px; height:30px;", #class = "frihrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SAT_HRS, new { style = "width:50px; height:30px;", #class = "sathrs" })
</td>
</tr>
</td>
}
and I want to bind data from database to all the fields , every thing is displaying data perfectly, but dropdown list for proj_id is not showing text even though i am passing value to dropdownlist. i am passing like :
public int GetTimsheetData(int empid, TimesheetModel TimesheetModel)
{
// GetimeSheet all the rows according employee name
var emps = (from n in db.TIMESHEETs
where n.RES_ID == empid
select n).ToList();
int count = emps.Count();
HttpContext.Current.Session["count"] = count;
try
{
List<TimesheetModel> emptyList = new List<TimesheetModel>();
TimesheetModel.GetTimeSheetDetails = emptyList; //taking Empty List and bind to GetTimesheetDetails for Add items into it.
//if Employee Name has more than one record.
if (emps.Count() > 0)
{
foreach (var timeSheet in emps)
{
TimesheetModel item = new TimesheetModel();
item.WEEK_CAL_ID = timeSheet.WEEK_CAL_ID;
item.PROJ_ID = timeSheet.PROJ_ID;
item.SUN_HRS = timeSheet.SUN_HRS;
item.MON_HRS = timeSheet.MON_HRS;
item.TUE_HRS = timeSheet.TUE_HRS;
item.WED_HRS = timeSheet.WED_HRS;
item.THU_HRS = timeSheet.THU_HRS;
item.FRI_HRS = timeSheet.FRI_HRS;
item.SAT_HRS = timeSheet.SAT_HRS;
TimesheetModel.GetTimeSheetDetails.Add(item);
}
}
}
catch (Exception ex)
{
throw ex;
}
return count;
}
and returning to controller like :
public ActionResult GetEmployeeDetails(int empId, string btn, TimesheetModel timesheetModel)
{
Employer_BL employerBL = new Employer_BL();
ViewBag.ProjectList = timesheetModel.getProjects;
//If GetTimesheetData returns morethan one record
if (employerBL.GetTimsheetData(empId, timesheetModel) >= 0)
{
timesheetModel.EMP_ID = empId;
//passes model data to View
return View("Timesheet", timesheetModel);
}
TimesheetModel model = new TimesheetModel();
model.EMP_ID = empId;
return View("Timesheet", model);
}
Where am I doing wrong, dropdownlist showing initial index instead of showing text of passing values. Please help me anyone.
in Separate Class I have written like below to get project names:
public SelectList getProjects()
{
IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
return new SelectList(projectslist, "Value", "Text", PROJ_ID);
}
It depends on the ViewBag.ProjectList which I cannot found on your source code. You could populate it with an object of type IEnumerable<SelectListItem> with one of the item Selected properties set to true.
public IEnumerable<SelectListItem> GetList()
{
return (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() }).ToList();
}
on your controller
ViewBag.ProjectList = GetList();
on your view
#{
var projectList =
new SelectList(ViewBag.ProjectList, "Value", "Text", Model.GetTimeSheetDetails[i].PROJ_ID.ToString())
}
#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, projectList, "-- Choose a Project --")
You can try like this method:
[NonAction]
private IEnumerable<SelectListItem> GetData()
{
return new List<SelectListItem>()
{
new SelectListItem(){ Text="--Select--", Value="0"},
new SelectListItem(){ Text="A", Value="1"},
new SelectListItem(){ Text="B", Value="2"},
new SelectListItem(){ Text="C", Value="3"},
};
}
Call this function in Action Method
public ActionResult Create()
{
ViewData["categories"] = GetData();
return View();
}
On your html page:
<%= Html.DropDownList("cat", (IEnumerable<SelectListItem>)ViewData["categories"])%>
You can use viewbag . in your controller you can read your data from the database :
public ActionResult Create()
{
ViewBag.ClassName = new SelectList(objclassrep.GetClasslist(), "Id", "ClassName");
}
And in your view model you can read the data from controller like this :
<div class="editor-label">
#Html.LabelFor(model => model.ClassId)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ClassId, (SelectList)ViewBag.ClassName);
#Html.ValidationMessageFor(model => model.ClassId)
</div>
This code automatically binds ids of your data to DDL Here is class id.
This is th getClassList function :
public List<Class> GetClasslist()
{
return _dbcontext.Classes.ToList();
}
i have a coded a radio button in MVC razor.below is the code for it.
#{
var LinkRadioName = "_Link";
var ContentRadioName ="_Content";
var TextRadioName = "_Text";
var ExternalLinkRadioName ="_ExternalLink";
var FilelistRadioName ="_Filelist";
#Html.RadioButtonFor(m => m.MenuType, true, new { #id = LinkRadioName })
#Html.Label("Link")
#Html.RadioButtonFor(m => m.MenuType, false, new { #id = ContentRadioName })
#Html.Label("Content")
#Html.RadioButtonFor(m => m.MenuType, true, new { #id = TextRadioName })
#Html.Label("Text")
#Html.RadioButtonFor(m => m.MenuType, false, new { #id = ExternalLinkRadioName })
#Html.Label("External Link")
#Html.RadioButtonFor(m => m.MenuType, true, new { #id = FilelistRadioName })
#Html.Label("File List")
}
can any one help me ,as to how can i access this radiobutton set in jquery:
i have a code like this
#Html.RadioButton("TypeOfmenu", 1)Link
#Html.RadioButton("TypeOfmenu", 2)Content
#Html.RadioButton("TypeOfmenu", 3)Text
#Html.RadioButton("TypeOfmenu", 4)ExternalLink
#Html.RadioButton("TypeOfmenu", 5)Filelist
and i access it very easily in jquery like
$("input[name$='TypeOfmenu']").click(function () {
var Selectedvalue = $(this).val();
});
is there any way to access the #Html.RadioButtonFor control in d same way like
$("input[name$='MenuType']").click(function () {
var Selectedvalue = $(this).val();
});
??????
please help me as i m very new in MVC as well as jquery.
Since you are accessing the values in your function with this.val(), you can just bind your event to all radio buttons
$(":radio").click(function () {
var Selectedvalue = $(this).val();
//OR
//var Selectedvalue = this.value;
});