This is my controller.
public class DokuzasController : Controller
{
public ActionResult AddOrEdit()
{
DersViewModel model = new DersViewModel();
schoolEntities sc = new schoolEntities();
List<ders> dersList = sc.ders.OrderBy(f => f.Ders1).ToList();
model.DersList = (from s in dersList
select new SelectListItem
{
Text = s.Ders1,
Value = s.DersID.ToString()
}).ToList();
model.DersList.Insert(0, new SelectListItem { Value = "", Text = "Select"});
return View(model);
}
[HttpPost]
public ActionResult AddOrEdit(DersViewModel model)
{
if (model.LectureId == 0)
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PostAsJsonAsync("dokuzas", model).Result;
TempData["SuccessMessage"] = "Saved.";
}
else
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PutAsJsonAsync("dokuzas/" + model.LectureId, model).Result;
TempData["SuccessMessage"] = "Successful.";
}
return RedirectToAction("Index");
}
[HttpPost]
public JsonResult SaatList(int id)
{
schoolEntities sc = new schoolEntities();
List<saat> saatList = sc.saat.Where(f => f.DersID == id).OrderBy(f => f.Saat1).ToList();
List<SelectListItem> itemList = (from i in saatList
select
new SelectListItem
{
Value = i.SaatID.ToString(),
Text = i.Saat1
}).ToList();
return Json(itemList, JsonRequestBehavior.AllowGet);
}
}
And this is my AddOrEdit file.
#model Mvc.Models.DersViewModel
#{
ViewBag.Title = "AddOrEdit";
}
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownListFor(m => m.DersID, Model.DersList)
<br /><br />
#Html.DropDownListFor(m => m.SaatID, Model.SaatList)
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#DersID").change(function () {
var id = $(this).val();
var saatList = $("#SaatID");
saatList.empty();
$.ajax({
url: '/Dokuzas/SaatList',
type: 'POST',
dataType: 'json',
data: { 'id': id },
success: function (data) {
$.each(data, function (index, option) {
saatList.append('<option value=' + option.Value + '>'
+ option.Text + '</option>')
});
}
});
});
});
</script>
}
I have a table and this table contains Dersadi and Dagilimi properties. I wanted to create a cascading list and add to table from this list from DersList to Dersadi and from SaatList to Dagilimi. But i choose items and select submit button i can submit it but it added null to the table. It did not add what i choose from the list. How can i fix this?
in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the Model.DersList. We will also add our second dropdown as well.
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownList("DersID", Model.DersList as SelectList)
<select name="id" id="SaatID" data-url="#Url.Action("SaatList","Home")">
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
<script type="text/javascript">
$(function(){
$("#DersID").change(function (e) {
var $SaatID = $("#SaatID");
var url = $SaatID.data("url")+'?id='+$(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
</script>
Related
I am working on an MVC application and I can not understand why I am getting few values as 'null'.
What should be done to serialize the date value from JavaScript to C#.
View code:
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="mvcCRUDApp">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("mvcCRUDApp", []);
app.service("crudAJService", function ($http) {
// save Customer
this.saveCustomer = function (objCustomer) {
var response = $http({
method: "post",
url: "Customer/PostDataResponse",
data: JSON.stringify(objCustomer),
dataType: "json"
});
return response;
}
});
app.controller("mvcCRUDCtrl", function ($scope, crudAJService) {
$scope.AddCustomer = function () {
var objCustomer = {
id: "0",
Name: $('#txtName').val(),
Surname: $('#txtSurname').val(),
BirthDate: $('#txtBirthDate').val(),
Gender: $('#txtGender').val(),
CityId: $('#drpCity').val()
};
var getBookData = crudAJService.saveCustomer(objCustomer);
getBookData.then(function (msg)
{
alert(msg.data);
}, function () {
alert('Error in updating book record');
});
}
});
</script>
<script>
$(document).ready(function ()
{
$("#drpState").change(function () {
$("#drpCity").empty();
$("#drpCity").append('<option value="0">-Select-</option>');
$.ajax({
type: 'POST',
url: '#Url.Action("SelectCities")',
dataType: 'json',
data: { Stateid: $("#drpState").val() },
success: function (cities) {
// cities contains the JSON formatted list
// of state id passed from the controller
$.each(cities, function (i, city)
{
$("#drpCity").append('<option value="'
+ city.id + '">'
+ city.Name + '</option>');
});
},
error: function (ex)
{
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
</head>
<body>
<div ng-controller="mvcCRUDCtrl">
<fieldset>
<table>
<tr><td>#Html.Label("Name")</td><td>#Html.TextBox("txtName")</td><td>#Html.Label("Surname")</td><td>#Html.TextBox("txtSurname")</td></tr>
<tr><td>#Html.Label("BirthDate")</td><td>#Html.TextBox("txtBirthDate")</td><td>#Html.Label("Gender")</td><td>#Html.TextBox("txtGender")</td></tr>
<tr>
<td>State</td>
<td>#Html.DropDownList("drpState", ViewBag.StateCollection as List<SelectListItem>)</td>
<td>City</td>
<td>#Html.DropDownList("drpCity", ViewBag.CityCollection as List<SelectListItem>)</td>
</tr>
<tr><td><input type="submit" value="Submit" ng-click="AddCustomer()" /></td></tr>
</table>
</fieldset>
</div>
</body>
</html>
Following is THE CODE OF CONTROLLER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DutchProject.Models;
namespace DutchProject.Controllers
{
public class CustomerController : Controller
{
DutchEntities db = new DutchEntities();
//
// GET: /Customer/
public ActionResult Index()
{
List<SelectListItem> States = new List<SelectListItem>();
var lstStates = db.States.ToList();
States.Add(new SelectListItem { Text = "-Select-", Value = "0" });
foreach (var item in lstStates)
{
States.Add(new SelectListItem { Text = item.Name, Value = item.id.ToString() });
}
ViewBag.StateCollection = States;
List<SelectListItem> Cities = new List<SelectListItem>();
Cities.Add(new SelectListItem { Text = "-Select-", Value = "0" });
ViewBag.CityCollection = Cities;
return View();
}
[HttpPost]
public JsonResult SelectCities(int Stateid)
{
IEnumerable<City> cities = db.Cities.Where(stat => stat.StateId == Stateid); // .Where(stat => stat.country_id == id);
return Json(cities);
}
[HttpPost]
public ContentResult PostDataResponse(Customer objCustomer)
{
objCustomer.BirthDate = DateTime.Now;
objCustomer.Gender = 1;
db.Customers.Add(objCustomer);
db.SaveChanges();
return Content("First name: " + Request.Form["firstName"] +
" | Last name: " + Request.Form["lastName"] +
" | Age: " + Request.Form["age"]);
}
}
}
ASP.NET MVC passes a null value in the controller action for a value that is not valid. It may help to validate the date beforehand, just to be sure the value is valid.
Also, it might help to assign a date instead of string:
...
var objCustomer = {
id: "0",
Name: $('#txtName').val(),
Surname: $('#txtSurname').val(),
BirthDate: new Date($('#txtBirthDate').val()),
Gender: $('#txtGender').val(),
CityId: $('#drpCity').val()
};
...
I have a drop down list which represent states and according to selected state, I need to refresh City drop down list which represent the cities in the selected state. How can I refresh the city drop down ?
Here is my code :
public class AccountController : Controller
{
public static List<SelectListItem> StateListItem()
{
var stateList = new List<SeraydarBL.Accounts.State>();
var selectListItems = new List<SelectListItem>();
stateList = SeraydarBL.Accounts.SelectStates();
foreach (var state in stateList)
{
var selectListItem = new SelectListItem();
selectListItem.Text = state.name;
selectListItem.Value = state.id.ToString();
selectListItems.Add(selectListItem);
}
return selectListItems;
}
}
here is the razor :
#using (Html.BeginForm())
{
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
//-------------------------------------------------------
var stateList = new List<SelectListItem>();
stateList = AccountController.StateListItem();
}
#Html.LabelFor(model => model.StateId)
#Html.DropDownListFor(model => model.StateId, stateList, " Select your State ...")
#Html.ValidationMessageFor(m => m.StateId)
#*HERE MUST BE THE DROP DOWN LIST OF CITIES*#
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
<script>
$('#StateId').change(function () {
});
</script>
}
You can achieve this using jquery ajax call.
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#StateId").change(function () {
$("#CityId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#StateId").val() },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityId").append('<option value="' + city.Value + '">' +``});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
refer few articles
http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/
I have to do one dropdownlist and one listbox. When I select a value in dropdownlist, the listbox has to change. I'm trying to do this with Jquery, because I'm using MVC. But when I select the ID in the first dropdownlist, nothing happens. My code:
View (Jquery):
<script type="text/javascript">
$(document).ready(function () {
$('#IDCONCESSAO').change(function () {
$.ajax({
url: '/Localidades/LocalidadesMunicipio',
type: 'POST',
data: { ConcessaoId: $(this).val() },
datatype: 'json',
success: function (data) {
var options = '';
$.each(data, function () {
options += '<option value="' + this.IdLocalidade + '">' + this.NomeLocalidades + '</option>';
});
$('#IDLOCALIDADE').prop('disabled', false).html(options);
}
});
});
});
</script>
Dropdownlist and listbox part:
<%: Html.DropDownListFor(model => model.SINCO_CONCESSAO, new SelectList(ViewBag.IDCONCESSAO, "Id", "Nome"), new { #class = "select", style = "width: 250px;" }) %>
</div>
<div class="editor-label" style="font-weight: bold">
Localidades:
</div>
<div class="editor-field" id="Localidades">
<%: Html.ListBoxFor(m => m.SelectedItemIds, Model.ItemChoices, new { id = "IDLOCALIDADE", size = "10" })%>
</div>
The action that do the cascade:
[HttpPost]
public ActionResult LocalidadesMunicipio(int ConcessaoID)
{
var Localidades = (from s in db.LOCALIDADES_VIEW
join c in db.SINCO_CONCESSAO.ToList() on s.ID_MUNICIPIO equals c.IDMUNICIPIO
where c.IDCONCESSAO == ConcessaoID
select new
{
idLocalidade = s.ID_LOCALIDADE,
NomeLocalidades = s.NOME_LOCALIDADE
}).ToArray();
return Json(Localidades);
}
Controller:
[Authorize(Roles = "ADMINISTRADOR")]
public ActionResult Create(SINCO_LOCALIDADE_CONCESSAO model)
{
//Here I populate my dropdownlist
ViewBag.IDCONCESSAO = from p in db.SINCO_CONCESSAO.ToList()
join c in db.MUNICIPIOS_VIEW.ToList() on p.IDMUNICIPIO equals c.ID_MUNICIPIO
join d in db.SINCO_TIPO_CONCESSAO.ToList() on p.IDTIPOCONCESSAO equals d.IDTIPOCONCESSAO
select new
{
Id = p.IDCONCESSAO,
Nome = p.IDCONCESSAO + " - " + c.NOME_MUNICIPIO + " - " + d.DSTIPOCONCESSAO
};
//Here I populate my listbox
PopulateItemLocalidades(model);
return View(model);
}
I can't see what is wrong T_T
What I am missing?
The first drop down most likely has an ID of SINCO_CONCESSAO, by the name of the property it was created for. And you are referring to something different in your script.
To fix this, either specify a different ID in jQuery:
$('#SINCO_CONCESSAO').ajax ...
or set an ID for a dropdown in View:
<%: Html.DropDownListFor(model => model.SINCO_CONCESSAO, ...
, new { id = "IDCONCESSAO" ... }) %>
In the create view what i am trying to do is when you choose a name from the dropdown list to fill the Login html.TextBoxFor automatically with his details.
Currently the Login textbox remains empty when i choose a person from dropdown list.
So i ve got my json object and tested as well my sql which is fine so i suppose the issue must be somewhere in jquery.
I would be glad if you could help me find the error.
View :
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">#Html.LabelFor(model => model.UserLogin)</div>
<div class="editor-field">#Html.TextBoxFor(model => model.UserLogin, new {id ="LoginId" })
#Html.ValidationMessageFor(model => model.UserLogin)</div>
<div class="editor-label">#Html.LabelFor(model => model.UserFullName)</div>
<div class="editor-field">#Html.DropDownList("UserFullName", ViewBag.UserFullName as SelectList, "Select a User", new { id = "UserID" })
#Html.ValidationMessageFor(model => model.UserFullName)</div>
<p>
<input type="submit"
value="Create" />
</p>
</fieldset> }
<div>#Html.ActionLink("Back to List", "Index")</div>
<script type="text/javascript">
$('#UserID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetUserForm")',
data: { FullName: $('#UserID').val() },
success: function (results){
var login = $('#LoginId');
login.empty();
$.each(results, function ()
{
login.val(this.ID).text(this.Value);
});
}});
});
</script>
Controller:
public ActionResult Create()
{
var names = StaffDB.StaffData.AsEnumerable().Select(s => new
{
ID = s.ID,
FullName = string.Format("{0} {1}", s.Forename1, s.Surname)
}).ToList();
if(ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserFullName = new SelectList(names, "FullName", "FullName", user.UserFullName);
return View(user);
}
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new
{
Value = s.Login,
ID = s.ID
};
return Json(data);
}
I think the issue is while returning the json, In MVC by default Jsonresult is "Deny get", so you have add "Allow Get".
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new { Value = s.Login, ID = s.ID };
if (data == null)
return Json(null);
return Json(data , JsonRequestBehavior.AllowGet);
}
I am very new to MVC, and am try to set up a series of cascading drop down lists using this example.
But I am stuck a little bit, because I don't know how to get the value from the second drop down and send it to controller when I press the appropriate button.
Here is my view:
<script type="text/javascript">
$('#list').change(function() {
var selectedClient = $(this).val();
if (selectedClient != null && selectedClient != '') {
$.getJSON('#Url.Action("SelectC")', { clientID: selectedClient }, function (client) {
var campaingSelect = $('#clist');
campaingSelect.empty();
$.each(client, function(index, clients) {
campaingSelect.append($('<option/>', {
value: clients.value,
text: clients.text
}));
});
});
}
});
</script>
#using (Html.BeginForm("CreateNewCampaign", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.LabelFor(m => m.alreadyCreatedCampaignName, "Name:")
#Html.DropDownList("clist","-- Select Client -2-")
<input type="Submit" name="button" value="Select" class="btn btn-primary" />
}
Controller:
public ActionResult SelectC(int clientId, CampaignModel model, FormCollection form)
{
Session["ClientID"] = clientId;
ViewBag.ClientName = "You're using: " + Session["ClientName"];
var CampaignInf = CampaignManagementService.GetCampaigns((string) Session["ticket"], clientId);
List<AlreadyCreatedCampaignList> itemas = new List<AlreadyCreatedCampaignList>();
foreach (var element in CampaignInf)
{
itemas.Add(new AlreadyCreatedCampaignList() {CampId = element.Key, CampName = element.Value});
}
var listOfCam = new SelectList(itemas, "campID", "campName", 1);
return Json(listOfCam.Select(x => new {value = x.Value, text = x.Text}), JsonRequestBehavior.AllowGet);
}
I want to get the value to other controller, and I am not sure of the right way to go about doing this.
You can get value of dropdownlist just by giving it ID and call $("#id").val();, then you can transfer it to the controller through ajax maybe.
Here is mine, try it
public ActionResult ActionName(string dropdown_value){
//your code
}
<script>
$(document).ready(function(){
$("submit").click(function(){
$.ajax({
url:"Controller/ActionName",
datatype: "POST",
data: { dropdown_value : $("#clist").val() },
success : function(){ //your code if success }
});
});
});
</script>