Add data from DropdownList to table(ASP.NET MVC) - c#

I have Companies table and Vacancies.
Company have some number of Vacancies
I have View like this
So I select company and second dropdown list is updated depending on company.
Here is View code (DropdownList section )
<div class="right-grid-in-grid" style="width:100%;">
<div style="margin-left:20px;width:50%; ">
#Html.DropDownList("Company", ViewBag.Companies as SelectList, new { #class = "greeting" })
#Html.ValidationMessageFor(model => model.VacancyId, "", new { #class = "text-danger" })
</div>
<div style="margin-left:20px;width:100%">
<select name="id" id="vacancy" style="width:55%" class="greeting" data-url="#Url.Action("Vacancies","Questions")" />
</div>
Here is code for AJAX request
$(function () {
$("#Company").change(function (e) {
var $vacancy = $("#vacancy");
var url = $vacancy.data("url") + '?companyId=' + $(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
And here is controller code
public ActionResult WelcomeScreen()
{
// Формируем список команд для передачи в представление
//SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
//ViewBag.Teams = teams;
ViewBag.Companies = new SelectList(db.Companies, "CompanyID", "CompanyName");
return View();
}
//Заносим инфу о вакансии в таблицу
[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
db.Interview.Add(interview);
db.SaveChanges();
return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });
}
My problem in this - I need to get VacancyId from second dropdownlist and write it to table.
All other data is writing well.
Not writing only VacancyId
Here is code of table
CREATE TABLE [dbo].[Interviews] (
[Interview_Id] INT IDENTITY (1, 1) NOT NULL,
[Greeting] NVARCHAR (MAX) NULL,
[Detail] NVARCHAR (MAX) NULL,
[VacancyId] INT NULL,
PRIMARY KEY CLUSTERED ([Interview_Id] ASC),
CONSTRAINT [FK_Interviews_ToTable] FOREIGN KEY ([VacancyId]) REFERENCES [dbo].[Vacancies] ([VacancyId]) ON DELETE CASCADE);

Thank's for all. I solve my problem yesterday
Here is code how to implement this using AJAX, in this AJAX call we get values from fields and pass them to backend.
Here is AJAX code:
<script>
$(document).ready(function () {
$('#save').click(function () {
save();
});
});
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
Detail: $('#Detail').val(),
Greeting: $('#Greeting').val(),
id: $('#vacancy').val(),
},
url: '#Url.Action("WelcomeScreenPost", "Questions")',
success: function (da) {
if (da.Result === "Success") {
window.location.href = da.RedirectUrl;
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
</script>
On backend we will write this in Controller action method.
[HttpPost]
public ActionResult WelcomeScreenPost(string Detail, string Greeting, int id)
{
Interview inter = new Interview
{
Greeting = Greeting,
Detail = Detail,
VacancyId = id,
};
db.Interview.Add(inter);
db.SaveChanges();
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Index", "Questions", new { id = inter.Interview_Id });
return Json(new { Result = "Success", Message = "Saved Successfully", RedirectUrl = url });
}
And all will works well.

Related

Cascading (Dependent) DropDownList using ASP.NET MVC

I have implemented Cascading (Dependent) DropDownList using ASP.NET MVC.
This is the tutorial
Now I need show alert message box after insert data and redirect on Index page in ASP.NET MVC.
To show alert message in ASP.NET MVC after insert data using store procedure from MySQL database, I have write the code like as shown below.
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
if (msg > 0)
{
alert("User Details Inserted Successfully");
window.location.href = "#Url.Action("Index", "Home")";
}
});
</script>
The data is correctly registered in the database table and the alert message box after insert data it's show.
But the redirect to index.cshtml not working because all the DropDownList on the form are empty except the first DropDownList that populates correctly.
window.location.href = "#Url.Action("Index", "Home")";
I mean that all other (populated cascading) DropDownList are enabled but empty.
I need redirect to Index Action page and being able to reload a new record, with this redirection it is impossible because the populated cascading DropDownList remain empty... instead of disabled and populated from value of first dropdownlist...
How to do resolve this?
Thanks.
Update 2021-01-02
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/DatePicker.js");
#Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
console.log(msg);
if (msg > 0)
{
alert("User Details Inserted Successfully");
var url = "#Url.Action("Index", "Home")";
window.location.href = url;
}
});
</script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
$("#thedate").datepicker(options);
$(function () {
$(".loading").hide();
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#TicketId");
DisableDropDown("#CityId");
dropDownId = "#TicketId";
list = response.Ticket;
PopulateDropDown("#TicketId", list);
break;
case "TicketId":
list = response.States;
DisableDropDown("#StateId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
dropDownId = "#CityId2";
list = response.Cities2;
PopulateDropDown("#CityId2", list);
$("#GPS").val(response.GPS);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option selected="selected" value="">[ === Select === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
var modal = $('<div />');
modal.addClass("modalBackground");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
setTimeout(function () {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
$(".loading").hide();
$('.modalBackground').remove();
}
}, 1000);
}
</script>
}
update controller
[HttpPost]
public ActionResult Index(PersonModel person)
{
MTsqlinsert(person); //Insert values in the database
if (ModelState.IsValid)
{
PersonModel personModel = new PersonModel();
person.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
person.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + countryId, "StateName", "StateId");
person.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + stateId, "CityName", "CityID");
ViewData["result"] = "1";
return RedirectToAction("Index");
}
return View(person);
}
[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
PersonModel personModel = new PersonModel
{
Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
};
return View(personModel);
}

Dependent dropdownlist in ASP.NET MVC

At present I have two tables (Teams and Employees)
I am populating the dropdownList for Teams perfectly, next I am trying to populate the second dropdownlist depending on the selectedId of Teams for Employees.
Controller:
// GET: CalView
public ActionResult Index(string ses, string DH)
{ //Team Lead Members
var eID = Convert.ToInt32(Session["currentEmployeeID"]);
var EmpID = Session["currentEmpID"];
Employee obj = (from o in db.Employees
where o.EnrollNumber == EmpID
select o).FirstOrDefault();
Department dept = (from dep in db.Departments
where dep.LeadBy == obj.EmployeeId
select dep).FirstOrDefault();
//this works fine
ViewBag.showTeams = new SelectList(db.Teams.Where(tm => (tm.DeptID == dept.DepartmentId) && (dept.LeadBy == eID)), "TeamID","Name");
//this obviously does not
ViewBag.showMembers = new SelectList(db.Employees.Where(empt => (empT.TeamID == selectedIdFromPreviousDropDownList), "EmployeeID", "Employee"));
return View();
}
View:
if ((Session["UT"] == "DD") && (#ViewBag.DeptLead != null))
{
//this works
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { #class = "form-control" })
//this does not work
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new { #class = "form-control" })
}
Do I need some AJAX call? or perhaps a POST method? Totally new to MVC.
Do I need some AJAX call? or perhaps a POST method? Okay then, lets do it this way:
Give your DropdownLists some id's probably:
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { id = "ddshowTeams", #class = "form-control" })
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new {id = "ddshowMembers", #class = "form-control" })
Create a jsonResult function, GetMembers and some Magic right there:
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#ddshowTeams").change(function () {
console.log("pehla andar");
$("#ddshowMembers").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetMembers")',
dataType: 'json',
data: { id: $("#ddshowTeams").val() },
success: function (mems) {
console.log("wich ayaeee");
// states contains the JSON formatted list
// of states passed from the controller
$.each(mems, function (i, member) {
$("#ddshowMembers").append('<option value="'
+ member.Value + '">'
+ member.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
and in your controller:
public JsonResult GetMembers(int id)
{
return Json(new SelectList(db.Employees.Where(empt => (empt.TeamId == id)), "EmployeeID", "FirstName"));
}

dropdown menu populate another c# mvc json ajax

Below is my code, I am not sure what i am doing wrong?
Ajax json jquery code
function FillCity() {
var countryid = $("select[name$='.countryid']").val(); //<---- this is dynamic
$.ajax({
url: "Controller/FillMyCity",
type: "POST",
dataType: "json",
data: { country: countryid } ,
success: function (city) {
$("select[name$='.cityid']").html(""); // <--- this is dynamic
$.each(city, function (i, pp) {
$("select[name$='.cityid']").append(
$('<option></option>').val(pp.cityid).html(pp.name));
});
},
error: function (err) {
alert(err);
}
});
}
Controller method
public JsonResult FillMyCity(int country)
{
var cities = db.Cities.Where(x => x.countryid == country).ToList().Select(item => new City
{
cityid = item.cityid,
name = item.name
}).AsQueryable();
return Json(cities, JsonRequestBehavior.AllowGet);
}
View
#Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { #class = "form-control countries", #id = "mycountry" + i + "", #onchange = "FillCity()" })
#Html.DropDownList("City[" + i + "].cityid", new SelectList(Enumerable.Empty<SelectListItem>(), "cityid", "name"), "Select city", new { #class = "form-control cities", #id = "mycity" + i + "" })
Output
EmployeeName Country City
Jenny ddl of countries ddl of cities
John ddl of countries ddl of cities
Problem 1: When I select country for Jenny, the cities ddl for both Jenny + John both get populated with Jenny's Country's cities, but it should only just applied for Jenny. When I select country for John the cities ddl list doesn't get populate So only Jenny's works, John doesn't
Problem 2: Since it is a dynamic json jquery appended html, I am unable to save the cities value, this is due to the fact that it is dynamic and doesn't appear in the view source.
Your use of $("select[name$='.countryid']").val(); will only ever select the value of the first element that has a name attribute ending with .countryid.
In addition, you use of DropDownList("Country[" + i + "].countryid", ...) is not the correct way to generate controls for a collection and its unlikely that will ever bind correctly to your model, however you have not shown the model so that cannot be fixed, so based on your current code, your view should be
<div class="container">
#Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { #class = "form-control countries" })
#Html.DropDownList("City[" + i + "].cityid", Enumerable.Empty<SelectListItem>(), new { #class = "form-control cities" })
</div>
and the script
$('.countries').change(function() {
var country = $(this).val();
var cities = $(this).next('.cities'); // get the associated cities dropdownlist
cities.empty(); // clear existing options
$.ajax({
url: '#Url.Action("FillMyCity")', // do not hard code url's
type: "POST",
dataType: "json",
data: { country: country } ,
success: function (data) {
if (data) {
cities.append($('<option></option>').val('').text('Select city'));
$.each(data, function (index, item) {
cities.append($('<option</option>').val(item.cityid).html(item.name));
});
} else {
// oops
}
},
error: function (err) {
alert(err);
}
});
});
and finally, return a collection of anonymous objects containing only the data you need in the view to avoid sending extra data that will not be used
public JsonResult FillMyCity(int country)
{
// No need for .ToList()
var cities = db.Cities.Where(x => x.countryid == country).Select(item => new
{
cityid = item.cityid,
name = item.name
});
return Json(cities); // its a POST so no need for JsonRequestBehavior.AllowGet
}

not able to display employee details in html table in view using json

I have got problem with displaying employee details in view when the user clicks the button on view..
when the user clicks the button the employee details(both id and name) will be called through the JSON and displaying data in html table, for that purpose I have written like this in my view
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = '/EmpDetails/GetEmployees/';
$.getJSON(url, function (data) {
$.each(data, function (key, Val) {
var user = '<tr><td>' + Val.EmployeeId + '<td><tr>' + '<tr><td>' + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
});
});
</script>
#{
ViewBag.Title = "GetEmployeesByName";
}
<h2>GetEmployeesByName</h2>
#using (Html.BeginForm())
{
<table id ="parenttable"></table>
<input id="submitbtnn" type="Submit" value="Submit1" />
}
and this is my controller, here i am returning json data to view
namespace MvcSampleApplication.Controllers
{
public class EmpDetailsController : Controller
{
[HttpGet]
public ActionResult GetEmployees()
{
List<EmployeeClass> employees = new List<EmployeeClass>();
EmployeeClass employee1 = new EmployeeClass { EmployeeId=1, EmployeeName = "Rams"};
EmployeeClass employee2 = new EmployeeClass { EmployeeId = 2, EmployeeName = "joseph" };
EmployeeClass employee3 = new EmployeeClass { EmployeeId = 3, EmployeeName = "matt" };
employees.Add(employee1);
employees.Add(employee2);
employees.Add(employee3);
return Json(employees, JsonRequestBehavior.AllowGet);
}
}
}
but I am getting http 404 resource not found error, when i am trying to access this url
http://localhost/EmpDetails
would any one pls suggest any ideas and any suggestions on this,that would be very greatful to me..
Many thanks...
Modified View
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = #Url.Action("GetEmployees","EmpDetails")
//alert("hi");
$.getJSON(url, function (data) {
//alert("hi");
$.each(data, function (Val) {
var user = '<tr><td>' + Val.EmployeeId + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
return false;
});
});
</script>
#{
ViewBag.Title = "GetEmployeesByName";
}
<h2>GetEmployeesByName</h2>
#using (Html.BeginForm())
{
<div class="temptable">
<table id ="parenttable"></table>
</div>
<input id="submitbtnn" type="Submit" value="Submit1" />
}
I am not able to hit second Alert Function inside JavaScript function.
You forgot to cancel the default action of the button by returning false from the click handler:
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = '/EmpDetails/GetEmployees/';
$.getJSON(url, function (data) {
$.each(data, function (key, Val) {
var user = '<tr><td>' + Val.EmployeeId + '<td><tr>' + '<tr><td>' + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
return false; // <!-- This is very important
});
By not canceling the default action, when you click on the submit button, the browser submits the form and redirects away from the page to the action of the form leaving no time for the AJAX request to ever execute.
Try using this as your url #Url.Action("GetEmployees","EmpDetails")
Try this
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
$.ajax({
url: 'GetEmployees',
type: 'POST',
data: JSON.stringify({ table: table }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var rowcount = data.employees.length;
for (var i = 0; i < rowcount; i++) {
var user = '<tr><td>' + employees[i].EmployeeId + employees[i].EmployeeName + '<tr><td>'
table.append(user);
}
});
},
error: function () {
alert('fail');
}
});
return false;
});

Selected values in cascading dropdownlists reset on post

I have MVC4 web-application with 2 cascading dropdownlists (parent and child) and button with post action for filtering data dislpayed in grid depending on selected values in dropdownlists. Cascading dropdownlists I realized with Microsoft AJAX (Ajax.BeginForm helper), almost as described here: http://weblogs.asp.net/raduenuca/archive/2011/03/20/asp-net-mvc-cascading-dropdown-lists-tutorial-part-3-cascading-using-microsoft-ajax-ajax-beginform-helper.aspx. BTW, dropdownlists are located in partial view.
The problem is that when I click button, postback is performed and selected values in cascading dropdownlists are reset to original values, i.e. "Please, select value".
Does anybody know how to solve this problem?
Thanks in advance for all who give an answers!
Here is my code with partial view with cascading dropdownlists:
<script type="text/javascript">
$(function () {
$('#Sections').change(function () {
var sectionId = $("#Sections :selected").val();
if (sectionId != "") {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetDocumentTypesList", "DocumentTypes")',
data: { "id": sectionId },
dataType: "json",
success: function (data) {
var items = "";
$.each(data, function (i, documentType) {
items += "<option value='" + documentType.Value + "'>" + documentType.Text + "</option>";
});
$('#Types').html(items);
},
error: function (result) {
alert('Service call failed: ' + result.status + ' Type :' + result.statusText);
}
});
}
else {
var items = '<option value="">Select</option>';
$('#Types').html(items);
}
});
});
#Html.DropDownList("Sections", new SelectList(ViewBag.Sections, "Id", "Name"), "Please select parent type", new { id = "Sections" })
#Html.DropDownList("Types", new SelectList(ViewBag.Types, "Id", "Name"), "Please select child type", new { id = "Types" })
And here is controller code for partial view:
public class DocumentTypesController : Controller
{
static List<DocumentType> documentTypes = DocumentsDAL.GetDocumentTypes(true, true, false);
// GET: /DocumentTypes/
public ActionResult Index()
{
var root = documentTypes.Where(d => d.ParentId == null).ToList();
ViewBag.Sections = root;
ViewBag.Types = new List<DocumentType> { new DocumentType { Id = -1, Name = "Select" } };
return PartialView("~/Views/Shared/_DocumentTypes.cshtml", root);
}
// Get values for parent dropdownlist.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetDocumentTypesList(string id)
{
var items = GetDocumentTypes(Convert.ToInt32(id)).Select(a => new SelectListItem
{
Text = a.Name,
Value = a.Id.ToString(CultureInfo.InvariantCulture)
});
return Json(items, JsonRequestBehavior.AllowGet);
}
// Get values for child dropdownlist.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetDocumentTypeData(string sectionId, string typeId)
{
var documentTypeData = GetDocumentTypes(Convert.ToInt32(sectionId))
.First(d => d.Id == Convert.ToInt32(typeId));
return Json(documentTypeData, JsonRequestBehavior.AllowGet);
}
private static IEnumerable<DocumentType> GetDocumentTypes(int id)
{
return documentTypes.First(d => d.Id == id).DocumentTypes;
}
}
And this is a base view where it's used partial one:
#using (Ajax.BeginForm("Index", null, new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "documentsGrid"
}, new { #class = "form-inline" }))
{
<div>
#{ Html.RenderAction("Index", "DocumentTypes", new { area = "" }); }
</div>
<p class="form-inline">
#Html.LabelForModel(#Resources.LabelPeriodFrom)
#Html.Raw(" ")
#Html.TextBox("periodFrom", "", new { #class = "input-small" })
#Html.Raw(" ")
#Html.LabelForModel(#Resources.LabelPeriodTo)
#Html.Raw(" ")
#Html.TextBox("periodTo", "", new { #class = "input-small" })
#Html.Raw(" ")
<input type="submit" class="btn" value="Filter" />
</p>
}
And controller for basic view with post-action Index, which fired when user press button:
public class IssuerDocumentsController : Controller
{
static readonly IEnumerable<IssuerDocument> Documents = DocumentsDAL.GetDocuments(1, 1).AsEnumerable();
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var documents = Documents.AsEnumerable();
// Check if document section filter is applied.
if (!string.IsNullOrEmpty(collection.Get("Sections")))
{
var documentSectionId = Convert.ToInt32(collection.Get("Sections"));
documents = documents.Where(d => d.SectionId == documentSectionId);
}
// Check if document type filter is applied.
if (!string.IsNullOrEmpty(collection.Get("Types")))
{
var documentTypeId = Convert.ToInt32(collection.Get("Types"));
documents = documents.Where(d => d.TypeId == documentTypeId);
}
return View(documents);
}
}

Categories

Resources