Rating Record Is Not getting save in database - c#

Controller=>>
view is sending data to SendRating and this method is responsible for storing data in database,,but data is not getting saved.
only authenticated user can rate ,but every time we faced rating failed..i can't understand what exactly the problem is.
public ActionResult SendRating(string r, string s, string id, string url)
{
try {
var context = new ApplicationDbContext();
string currentUserId = User.Identity.GetUserId();
int autoid = 0;
Int16 thisVote = 0;
Int16 O_ServID = 0;
Int16.TryParse(s, out O_ServID);
Int16.TryParse(r, out thisVote);
int.TryParse(id, out autoid);
if (!User.Identity.IsAuthenticated)
{
return Json("Not authenticated!");
}
switch (s)
{
case "5":
//var isIt = db.VoteModel.Where(v => v.O_ServID == O_ServID && v.UserId.Equals(User.Identity.Name, StringComparison.CurrentCultureIgnoreCase) && v.WorkerID == autoid).FirstOrDefault();
var service = context.OrderServices.Where(o => o.O_ServID == O_ServID).Single();
var worker = context.Workers.Where(w => w.WorkerID == autoid).Single();
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
var user = userManager.FindByName(User.Identity.Name);
VoteModel vm = new VoteModel()
{
Active = true,
//id
UserId = User.Identity.GetUserId(),
Votes = thisVote,
WorkerID = autoid,
O_ServID = O_ServID,
OrderServices = service,Workers = worker,User = user
};
var save = context.VoteModel.Add(vm);
if(db.SaveChanges() > 0)
{
HttpCookie cookie = new HttpCookie(url, "true");
Response.Cookies.Add(cookie);
return Json("<br />You rated " + r + " star(s), thanks !", JsonRequestBehavior.AllowGet);
}
// keep the school voting flag to stop voting by this member
//HttpCookie cookie = new HttpCookie(url, "true");
//Response.Cookies.Add(cookie);
//}
break;
default:
break;
}
return Json("Rating Failed!", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
HttpCookie cookie = new HttpCookie(url, "true");
Response.Cookies.Add(cookie);
return Json(ex.Message, JsonRequestBehavior.AllowGet);
throw;
}
}
public ActionResult VoteNow(int id, int serv)
{
ViewData["id"] = id;
ViewData["serv"] = serv;
return View();
}
public ActionResult VoteShow()
{
return View();
}
Model==>>
this is table schema where record has to be stored..
namespace WebApplication5.Models
{
public class VoteModel
{
[Key]
public int AutoId { get; set; }
public int O_ServID { get; set; }
public OrderService OrderServices { get; set; }
public int WorkerID { get; set; }
public Worker Workers { get; set; }
public Int16 Votes { get; set; }
public bool Active { get; set; }
[Required]
public string UserId { get; set; }
public ApplicationUser User { get; set; }
}
}
view==>>
my view code is as follows...
sending data with json to controller with different parameters pass through ViewData[] ..
#{
ViewBag.Title = "VoteNow";
Layout = "~/Views/Shared/_LayoutUser.cshtml";
}
<div id="page-wrapper">
<div id="page-inner">
<h2>VoteNow</h2>
#model string
#{
var url = Request.Url.AbsolutePath;
}
#if (Request.Cookies[url] == null)
{
<div id="ratingDiv" class="smallText">
Poor
<img src="/img/whitestar.gif" alt="" class="ratingStar" data-value="1" /><img src="/img/whitestar.gif" alt="" class="ratingStar" data-value="2" /><img src="/img/whitestar.gif" alt="" class="ratingStar" data-value="3" /><img src="/img/whitestar.gif" alt="" class="ratingStar" data-value="4" /><img src="/img/whitestar.gif" alt="" class="ratingStar" data-value="5" /> Excellent
<label id="lblResult"></label>
</div>
<style type="text/css">
.ratingStar {
cursor: pointer;
height: 20px;
width: 20px;
}
</style>
}
else
{
<text><span style="color:green;"> Thanks for your vote !</span></text>
}
#section scripts{
<script type="text/javascript">
var clickedFlag = false;
$(".ratingStar").mouseover(function () {
$(this).attr("src", "/img/yellowstar.gif").prevAll("img.ratingStar").attr("src", "/img/yellowstar.gif");
});
$(".ratingStar, #radingDiv").mouseout(function () {
$(this).attr("src", "/img/whitestar.gif");
});
$("#ratingDiv").mouseout(function () {
if (!clickedFlag) {
$(".ratingStar").attr("src", "/img/whitestar.gif");
}
});
$(".ratingStar").click(function () {
clickedFlag = true;
$(".ratingStar").unbind("mouseout mouseover click").css("cursor", "default");
var url = "/CDashboard/SendRating?r=" + $(this).attr("data-value") + "&s=#((int)ViewData["serv"])&id=#((int)ViewData["id"])&url=#url";
$.post(url, null, function (data) {
$("#lblResult").html(data);
});
});
$("#lblResult").ajaxStart(function () {
$("#lblResult").html("Processing ....");
});
$("#lblResult").ajaxError(function () {
$("#lblResult").html("<br />Error occured.");
});
</script>
}
</div>
</div>

Related

Submit form through existing API URL and get JSON response

Im new to API,
Below is my scenario, Where i need help. My code may have many issues, kindly help me to learn this. :)
I have an existing API URL, and My objective is to POST request to that existing API URL while submitting a form and get below JSON response
{
"success": true,
"message": "GOOD",
"data": null
}
.cshtml code
#section Scripts {
<script type="text/javascript">
$("#form1").submit(function () {
var Serial = $.post('http://mesappbeta/BE_API_HOME/api/SeriesBlacklist/Req_DBL', $('#form1').serialize())
.success(function () {
var path = Serial.getResponseHeader('Location');
var i = $('<a/>', { href: path, text: path });
$('#message').html(i);
})
.error(function () {
$('#message').html("Error for changes.");
});
return false;
});
</script>
}
<div>
<form Id="form1" method="post" action="http://mesappbeta/BE_API_HOME/api/SeriesBlacklist/Req_DBL" enctype="application/x-www-form-urlencoded">
<asp:Panel ID="pnlGrid" runat="server" Visible="true">
<table>
<tr>
<td style="width: 25%; height: 30px">
<div>
<label for="name">Special Instruction:</label>
<asp:CheckBox ID="CheckBox1" runat="server" />
</div>
</td>
</tr>
<tr>
<td style="width: 25%; height: 30px">
<div>
<label for="name" style="display: block">Notes: </label>
<textarea style="display: block"></textarea>
</div>
</td>
</tr>
<tr>
<td style="width: 25%; height: 30px">
</br>
<div>
<input type="submit" value="Submit" />
#*<button style="width:fit-content" name="StartRequest" value="StartRequest">Start Request</button>*#
</div>
</td>
<th style="border:inherit">
</th>
</tr>
</table>
</asp:Panel>
</form>
</div>
CONTROLLER
using DocumentFormat.OpenXml.ExtendedProperties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WebApplication9.Models;
namespace WebApplication9.Controllers
{
using WebApplication9.Models;
public class ChangesController : ApiController
{
static readonly Dictionary<Guid, Change> _changes = new Dictionary<Guid, Change>();
[HttpPost]
[ActionName("Code")]
public HttpResponseMessage PostComplex(Change change)
{
if(ModelState.IsValid && change != null)
{
change.Notes = HttpUtility.HtmlEncode(change.Notes);
var Id = Guid.NewGuid();
_changes[Id] = change;
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(change.Notes)
};
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { action = "type", Id = Id }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
[HttpPost]
[ActionName("Decode")]
public HttpResponseMessage PostSimple([FromBody] string value)
{
if(value != null)
{
Change change = new Change()
{
Notes = HttpUtility.HtmlEncode(value)
};
var Id = Guid.NewGuid();
_changes[Id] = change ;
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(change.Notes)
};
response.Headers.Location = new Uri(Url.Link("DefaultApi", new {action = "type", Id=Id }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
[HttpGet]
public Change Notes(Guid Id)
{
Change change;
if(_changes.TryGetValue(Id, out change))
{
return change;
}
else
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
}
}
}
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace WebApplication9.Models
{
public class Change
{
public string Notes { get; set; }
}
}
Webapiconfig.cs
namespace WebApplication9
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
}
I TRIED : POST existing API URL through Submit button of a webform.
Expected to get below response :
{
"success": true,
"message": "GOOD",
"data": null
}
But getting below error message :
Hi #Guru you can add generic API response wrapper to return you response.
public class ServiceResponse<T>
/// <summary>
/// Generic wrapper for web api response.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ServiceResponse<T>
{
public T Data { get; set; }
public bool Success { get; set; } = true;
public string Message { get; set; } = null;
public string Error { get; set; } = null;
public List<string> ErrorMessages { get; set; } = null;
}
How to use it:
ServiceResponse<NoteModel> _response = new();
_response.Success = true;
_response.Data = NoteModel;
_response.Message = "Created";
return _response;
Here is an example for both HttpResponseMessage and IHttpActionResult. I have tested both and they work.
[HttpPost]
[ActionName("Code")]
public HttpResponseMessage PostComplex(SampleViewModel change)
{
if (ModelState.IsValid && change != null)
{
ServiceResponse<SampleViewModel> _response = new ServiceResponse<SampleViewModel>();
var newGuid = Guid.NewGuid().ToString();
change.Id = newGuid;
if (!string.IsNullOrWhiteSpace(change.Id))
{
// ...
_response.Data = change;
_response.Success = true;
_response.Message = "Created";
return Request.CreateResponse(_response);
}
// ...
_response.Data = change;
_response.Success = false;
_response.Message = "Failed";
return Request.CreateResponse(_response);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
[HttpPost]
[ActionName("Code")]
public IHttpActionResult PostComplex2(SampleViewModel change)
{
if (ModelState.IsValid && change != null)
{
ServiceResponse<SampleViewModel> _response = new ServiceResponse<SampleViewModel>();
var newGuid = Guid.NewGuid().ToString();
change.Id = newGuid;
if (!string.IsNullOrWhiteSpace(change.Id))
{
// ...
_response.Data = change;
_response.Success = true;
_response.Message = "Created";
return Ok(_response);
}
// ...
_response.Data = change;
_response.Success = false;
_response.Message = "Failed";
return Ok(_response);
}
else
{
return BadRequest();
}
}
public class SampleViewModel
{
[Required]
[MinLength(10)]
[MaxLength(100)]
[Display(Name = "Ask Magic 8 Ball any question:")]
public string Question { get; set; }
public string Id { get; set; }
//See here for list of answers
public string Answer { get; set; }
}
public class ServiceResponse<T>
{
public T Data { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public string Error { get; set; }
public List<string> ErrorMessages { get; set; }
}

How would i get the data from each event from a jsonResult with full calendar

I'm attempting to get event data (Title, date,etc) for an event when clicked but I can't figure out a way to do it since I add the data through the JSON result and full calendar javascript. If I cant, is there a better way to allow the backend razorpage to send data to the full calendar javascript?
backend
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using DynaHealth.Models;
using Microsoft.AspNetCore.Http;
namespace TeleHealthB.Pages
{
public class CalendarModel : PageModel
{
// public IndexModel(TeleHealthB.Models.HealthProjectContext context)
//{
// healthProject = context;
//}
[BindProperty]
public string Title { get; set; }
[BindProperty]
public string Doc { get; set; }
[BindProperty]
public string Pat { get; set; }
[BindProperty]
public string dec { get; set; }
[BindProperty]
public DateTime date { get; set; }
[BindProperty]
public JsonResult result { get; set; }
public string today = DateTime.Today.ToString();
public void OnGet()
{
// result = (JsonResult)OnGetEvents();
}
public class eventShow
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string start { get; set; }
public string end { get; set; }
//public string description { get; set; }
// public string patient { get; set; }
// public string doctor { get; set; }
}
private DynaHealth2Context db;
public CalendarModel(DynaHealth2Context _db)
{
db = _db;
}
public IActionResult OnGetEvents()
{
List<eventShow> events = new List<eventShow>();
eventShow show = new eventShow();
try
{
string x = HttpContext.Session.GetString("Username");
using (var context = new DynaHealth2Context())
{
var query = from st in context.Appointments
where st.PatientEmail == x.Trim() || st.ProviderEmail == x.Trim()
select st;
// foreach (var item in query.ToList())
// {
// show.id = item.Id;
// show.title = item.Title;
// show.description = item.Description;
// show.start = item.Start.ToString("MM/dd/yyyy");
//show.end = item.End.ToString("MM/dd/yyyy");
// events.Add(show);
// }
return new JsonResult(query.ToList());
}
}
catch { return null; }
}
public IActionResult OnGetADDEvent(string sub)
{
// using (var context = new HealthProjectContext())
{
try
{
//context.Schedules.Add(schedule);
return null;
}
catch { return null; };
}
}
// public onPost()
// {
// RedirectToPage("./Meeting");
// }
public IActionResult OnPostRemoveEvent(string sub)
{
// using (var context = new HealthProjectContext())
{
try
{
// context.Schedules.Add(schedule);
return null;
}
catch { return null; };
}
}
}
}
frontend
#model TeleHealthB.Pages.CalendarModel
#{
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Calendar</title>
<link href='~/lib/TestCalendar/main.css' rel='stylesheet' />
<script src='~/lib/TestCalendar/main.js'></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
initialDate: Date.now(),
navLinks: true, // can click day/week names to navigate views
selectable: true,
selectMirror: true,
select: function (arg) {
var title = prompt('Reasining For meeting:');
if (title) {
var tie = prompt('Time');
}
if (title) {
calendar.addEvent({
title: title,
start: arg.start,
Starttime: tie,
end: arg.end,
EndTime: arg.EndTime
})
}
calendar.unselect()
},
eventClick: function (event, jsEvent, view) {
window.open("/Meeting", "_blank");
return false
},
editable: false,
dayMaxEvents: true, // allow "more" link when too many events
events: "/calendar?handler=events"
});
calendar.render();
});
</script>
<style>
#calendar {
max-width: 1100px;
margin: 0 auto;
}
</style>
</head>
<body>
<h1>Schedule View</h1>
<div id='calendar'></div>
<div id="fullCalModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="false">x</span>
<span class="sr-only">Close</span>
</button>
<h4 id="modalTItle" class="modal-title"> </h4>
</div>
<div id="modalBody" class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" name="del" class="btn btn-default" id="eventURL">Delete</button>
<a class="btn btn-primary" id="eventURL" target="_blank">Schedule</a>
</div>
</div>
</div>
</div>
</body>
</html>
}
If you want to get the event in the backend,you can do following change:
You can use code var events = calendar.getEvents(); to get all the events,and then push the property you want in the array,the pass the arry to the backend.
Frontend
//Add a button to get event:
<button id="GetEvent">Get Event</button>
//....
document.addEventListener('DOMContentLoaded', function () {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
initialDate: Date.now(),
navLinks: true, // can click day/week names to navigate views
selectable: true,
selectMirror: true,
select: function (arg) {
var title = prompt('Reasining For meeting:');
if (title) {
var tie = prompt('Time');
}
if (title) {
calendar.addEvent({
title: title,
start: arg.start,
Starttime: tie,
end: arg.end,
EndTime: arg.EndTime
})
}
calendar.unselect()
},
eventClick: function (event, jsEvent, view) {
window.open("/Meeting", "_blank");
return false
},
editable: false,
dayMaxEvents: true, // allow "more" link when too many events
events: "/calendar?handler=events"
});
calendar.render();
//add following
$("#GetEvent").click(function () {
var events = calendar.getEvents();
var e = [];
$.each(events, function (index, value) {
console.log(value.start);
console.log(index);
var start_time = value.start;
var end_time = value.end;
var id = parseInt(value.id);
var slot = {
start: start_time,
end: end_time,
id: id,
};
e.push(slot);
});
$.ajax({
url: '/test?handler=getevents',
contentType:"application/json",
data: JSON.stringify(e),
dataType: "json",
type: "POST",
});
});
});
Backend:
//add this line
[IgnoreAntiforgeryToken]
public class TestModel : PageModel
{
[BindProperty]
public string Title { get; set; }
[BindProperty]
public string Doc { get; set; }
[BindProperty]
public string Pat { get; set; }
[BindProperty]
public string dec { get; set; }
[BindProperty]
public DateTime date { get; set; }
//delete this line
//[BindProperty]
public JsonResult result { get; set; }
public string today = DateTime.Today.ToString();
public void OnGet()
{
JsonResult result = (JsonResult)OnGetEvents();
}
public class eventShow
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string start { get; set; }
public string end { get; set; }
}
public IActionResult OnGetEvents()
{
}
public void OnPostGetEvents([FromBody]List<eventShow> model)
{
}
Test result:

How to keep your model values on a return View after a ModelState.IsValid

I'm still quite new to ASP.NET-MVC so i'm still a bit confused about returns and redirects and DropDownListFor values.
I have a view where a user inserts data to add to a database. Most of the data comes from DropDownLists, where the Lists are stored in the model. The lists are initiated once you enter the page for the first time, filling the model. Once you submit, the HttpPost on the Controller has a "ModelState.IsValid", and returns to the same page with the errors. The problem is, all the lists i had filled are now empty and the DropDownListFor are all empty.
Is there a way to keep the model with its values? Also, is there a way to keep the values previously entered on a DropDownListFor on return?
View Code:
#using Encomendas_WebFinal.Models
#{
ViewBag.Title = "Encomenda";
}
#model ClientModel
<link rel="stylesheet" href="~/Content/zebra_datepicker.min.css" />
<script src="~/Scripts/zebra_datepicker.min.js"></script>
<h1>Encomenda</h1>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-group">
<h3>Encomenda:</h3>
<fieldset>
<p>#Html.DropDownListFor(m => m.SelectedEncomenda.NumEncomenda, Model.ListEncomendas, "")</p>
#Html.ValidationMessageFor(m => m.SelectedEncomenda.NumEncomenda)
</fieldset>
<h3>Data:</h3>
#Html.EditorFor(m => m.SelectedEncomenda.Data, new { htmlAttributes = new { #class = "calendar"} })
<h3>Tipo de Infraestrutura:</h3>
<input type="radio" name="selectedLinhaType" id="150KV"/> 150kV <br>
<input type="radio" name="selectedLinhaType" id="220KV"/> 220KV <br>
<input type="radio" name="selectedLinhaType" id="400KV"/> 440KV <br>
<input type="radio" name="selectedLinhaType" id="Gasodutos" /> Gasodutos <br>
<input type="radio" name="selectedLinhaType" id="Patrimonios" /> Patrimonios <br>
<div class ="infobox" id="is150KV">
<fieldset>
<h3>Linha 150KV:</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, Model.ListLinha150, new { disabled = "disabled", #id="Linha150KV"})</p>
</fieldset>
</div>
<div class ="infobox" id="is220KV">
<fieldset>
<h3>Linha 220KV:</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, Model.ListLinha220, new { disabled = "disabled", #id = "Linha220KV" })</p>
</fieldset>
</div>
<div class="infobox" id="is400KV">
<fieldset>
<h3>Linha 400KV:</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, Model.ListLinha400 as List<SelectListItem>, new { disabled = "disabled", #id = "Linha400KV" })</p>
</fieldset>
</div>
<div class="infobox" id="isGasoduto">
<fieldset>
<h3>Gasoduto:</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, Model.ListGasodutos, new { disabled = "disabled", #id = "Gasoduto" })</p>
</fieldset>
</div>
<div class="infobox" id="isPatrimonio">
<h4> Patrimonio Selected</h4>
</div>
</div>
<h3>Concelho:</h3>
<fieldset>
<p>#Html.DropDownListFor(m => m.SelectedConcelho, Model.ListConcelhos, "")</p>
</fieldset>
<h3>Numero de Tecnicos de Aviso: #Html.TextBoxFor(m => m.SelectedEncomenda.TecnicoAvisoNum, new { type = "number", min = "0", max = "3", step = "1", value = "0", #id="TecnicoAvisoNum" }) </h3>
<div class="infobox" id="TecnicoAviso1">
<h4> Tecnico Aviso 1</h4>
</div>
<div class="infobox" id="TecnicoAviso2">
<h4> Tecnico Aviso 2</h4>
</div>
<div class="infobox" id="TecnicoAviso3">
<h4> Tecnico Aviso 3</h4>
</div>
<div class="infobox" id="TecnicoAvisoErro">
<h2> Por favor insira um valor inteiro entre 0 e 3.</h2>
</div>
<input type="submit" value="Post" />
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$('.calendar').Zebra_DatePicker({
show_week_number: 'Wk',
format: 'd/m/Y'
});
$('#is150KV').hide(); $('#is220KV').hide(); $('#is400KV').hide(); $('#isGasoduto').hide(); $('#isPatrimonio').hide();
$('#TecnicoAviso1').hide(); $('#TecnicoAviso2').hide(); $('#TecnicoAviso3').hide(); $('#TecnicoAvisoErro').hide();
$('#150KV').change(function () {
$('#is220KV').hide(); $('#is400KV').hide(); $('#isGasoduto').hide(); $('#isPatrimonio').hide();
$('#is150KV').show();
$('#Linha220KV').attr('disabled', true); $('#Linha400KV').attr('disabled', true); $('#Gasoduto').attr('disabled', true);
$('#Linha150KV').removeAttr('disabled');
});
$('#220KV').change(function () {
$('#is150KV').hide(); $('#is400KV').hide(); $('#isGasoduto').hide(); $('#isPatrimonio').hide();
$('#is220KV').show();
$('#Linha150KV').attr('disabled', true); $('#Linha400KV').attr('disabled', true); $('#Gasoduto').attr('disabled', true);
$('#Linha220KV').removeAttr('disabled');
});
$('#400KV').change(function () {
$('#is150KV').hide(); $('#is220KV').hide(); $('#isGasoduto').hide(); $('#isPatrimonio').hide();
$('#is400KV').show();
$('#Linha150KV').attr('disabled', true); $('#Linha220KV').attr('disabled', true); $('#Gasoduto').attr('disabled', true);
$('#Linha400KV').removeAttr('disabled');
});
$('#Gasodutos').change(function () {
$('#is150KV').hide(); $('#is220KV').hide(); $('#is400KV').hide(); $('#isPatrimonio').hide();
$('#isGasoduto').show();
$('#Linha150KV').attr('disabled', true); $('#Linha220KV').attr('disabled', true); $('#Linha400KV').attr('disabled', true);
$('#Gasoduto').removeAttr('disabled');
});
$('#TecnicoAvisoNum').change(function () {
if ($('#TecnicoAvisoNum').val() == 0) {
$('#TecnicoAviso1').hide(); $('#TecnicoAviso2').hide(); $('#TecnicoAviso3').hide(); $('#TecnicoAvisoErro').hide();
}
else
if ($('#TecnicoAvisoNum').val() == 1) {
$('#TecnicoAviso1').show(); $('#TecnicoAviso2').hide(); $('#TecnicoAviso3').hide(); $('#TecnicoAvisoErro').hide();
}
else
if ($('#TecnicoAvisoNum').val() == 2) {
$('#TecnicoAviso1').hide(); $('#TecnicoAviso2').show(); $('#TecnicoAviso3').hide(); $('#TecnicoAvisoErro').hide();
}
else
if ($('#TecnicoAvisoNum').val() == 3) {
$('#TecnicoAviso1').hide(); $('#TecnicoAviso2').hide(); $('#TecnicoAviso3').show(); $('#TecnicoAvisoErro').hide();
}
else
{
$('#TecnicoAviso1').hide(); $('#TecnicoAviso2').hide(); $('#TecnicoAviso3').hide(); $('#TecnicoAvisoErro').show();
}
});
})
</script>
}
}
Controller:
using Encomendas_WebFinal.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
namespace Encomendas_WebFinal.Controllers
{
public class EncomendaController : BaseController
{
ClientModel cliente = new ClientModel();
ConcelhosModel concelhos = new ConcelhosModel();
//DB CONNECTION STRING
private static string GetSQLConnectionString()
{
string cstr =
"Server=localhost;Database=REN_Encomendas;User Id=admin;Password=admin;";
return cstr;
}
//GET DB TABLE
private static DataSet ExecuteQuery(string query)
{
SqlConnection dbConnection;
SqlCommand dbCommand;
DataSet objDataSet;
SqlDataAdapter objAdapter;
dbConnection = new SqlConnection();
dbConnection.ConnectionString = GetSQLConnectionString();
dbConnection.Open();
objAdapter = new SqlDataAdapter();
objDataSet = new DataSet();
dbCommand = new SqlCommand(query);
dbCommand.Connection = dbConnection;
objAdapter.SelectCommand = dbCommand;
objAdapter.Fill(objDataSet);
dbCommand.Dispose();
objAdapter.Dispose();
dbConnection.Dispose();
dbConnection.Close();
return objDataSet;
}
//GET PostEncomenda
public ActionResult PostEncomenda()
{
//Initiate Data
cliente.ListaEncomendas = GetEncomendasList();
concelhos.Nomes = GetConcelhos();
concelhos.Linhas150 = GetLinhas("150");
concelhos.Linhas220 = GetLinhas("220");
concelhos.Linhas400 = GetLinhas("400");
concelhos.Gasoduto = GetGasodutos();
//Makes a DropDownList for Encomendas
List<SelectListItem> ListEncomenda = new List<SelectListItem>();
for (int i = 0; i< cliente.ListaEncomendas.Count; i++)
{
ListEncomenda.Add(new SelectListItem
{
Text = cliente.ListaEncomendas[i].NumEncomenda.ToString() + " -- " + cliente.ListaEncomendas[i].NomeEncomenda,
Value = cliente.ListaEncomendas[i].NumEncomenda.ToString() + "-_-_-" + cliente.ListaEncomendas[i].NomeEncomenda,
});
}
//Makes a DropDownList for Linhas
List<SelectListItem> ListLinhas150 = new List<SelectListItem>();
for (int i = 0; i< concelhos.Linhas150.Count; i++)
{
ListLinhas150.Add(new SelectListItem
{
Text = concelhos.Linhas150[i].NumLinha + " -- " + concelhos.Linhas150[i].NomeLinha,
Value = concelhos.Linhas150[i].NumLinha + "-_-_-" + concelhos.Linhas150[i].NomeLinha,
});
}
List<SelectListItem> ListLinhas220 = new List<SelectListItem>();
for (int i = 0; i < concelhos.Linhas220.Count; i++)
{
ListLinhas220.Add(new SelectListItem
{
Text = concelhos.Linhas220[i].NumLinha + " -- " + concelhos.Linhas220[i].NomeLinha,
Value = concelhos.Linhas220[i].NumLinha + "-_-_-" + concelhos.Linhas220[i].NomeLinha,
});
}
List<SelectListItem> ListLinhas400 = new List<SelectListItem>();
for (int i = 0; i < concelhos.Linhas400.Count; i++)
{
ListLinhas400.Add(new SelectListItem
{
Text = concelhos.Linhas400[i].NumLinha + " -- " + concelhos.Linhas400[i].NomeLinha,
Value = concelhos.Linhas400[i].NumLinha + "-_-_-" + concelhos.Linhas400[i].NomeLinha,
});
}
//Makes a DropDownList for Gasodutos
List<SelectListItem> ListGasodutos = new List<SelectListItem>();
for (int i = 0; i < concelhos.Gasoduto.Count; i++)
{
ListGasodutos.Add(new SelectListItem
{
Text = concelhos.Gasoduto[i].NumLinha + " -- " + concelhos.Gasoduto[i].NomeLinha,
Value = concelhos.Gasoduto[i].NumLinha + "-_-_-" + concelhos.Gasoduto[i].NomeLinha,
});
}
//Makes a DropDownList for Concelhos
List<SelectListItem> ListConcelhos = new List<SelectListItem>();
for (int i = 0; i < concelhos.Nomes.Count; i++)
{
ListConcelhos.Add(new SelectListItem
{
Text = concelhos.Nomes[i],
Value = concelhos.Nomes[i]
});
}
cliente.ListLinha150 = ListLinhas150;
cliente.ListLinha220 = ListLinhas220;
cliente.ListLinha400 = ListLinhas400;
cliente.ListGasodutos = ListGasodutos;
cliente.ListConcelhos = ListConcelhos;
cliente.ListEncomendas = ListEncomenda;
cliente.SelectedEncomenda = new PostEncomendaModel();
return View(cliente);
}
//POST PostEncomenda
[HttpPost]
public ActionResult PostEncomenda(ClientModel viewModel)
{
if(ModelState.IsValid)
{
//Test Stuff
PostEncomendaModel encomenda = new PostEncomendaModel();
string[] encomendaNumNome = viewModel.SelectedEncomenda.NumEncomenda.Split(new[] { "-_-_-" }, StringSplitOptions.None);
encomenda.NumEncomenda = encomendaNumNome[0];
encomenda.NomeEncomenda = encomendaNumNome[1];
encomendaNumNome = viewModel.SelectedLinha.NumLinha.Split(new[] { "-_-_-" }, StringSplitOptions.None);
encomenda.Linha = new Linhas();
encomenda.Linha.NomeLinha = encomendaNumNome[0];
encomenda.Linha.NumLinha = encomendaNumNome[1];
encomenda.Data = viewModel.SelectedEncomenda.Data;
TempData["Encomenda"] = encomenda;
return RedirectToAction("Teste", "Encomenda");
}
return View(viewModel);
}
//GET Submit Test
[HttpGet]
public ActionResult Teste(PostEncomendaModel model)
{
PostEncomendaModel encomenda = new PostEncomendaModel();
encomenda = (PostEncomendaModel)TempData["Encomenda"];
ViewBag.EncomendaNum = encomenda.NumEncomenda;
ViewBag.EncomendaNome = encomenda.NomeEncomenda;
ViewBag.LinhaNum = encomenda.Linha.NumLinha;
ViewBag.LinhaNome = encomenda.Linha.NomeLinha;
ViewBag.Data = Convert.ToDateTime(encomenda.Data);
DateTime tempdata = ViewBag.Data;
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(tempdata);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
tempdata = tempdata.AddDays(3);
}
ViewBag.Semana = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(tempdata, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return View();
}
//GET ALL ENCOMENDAS FROM DB FOR THE SELECTED CLIENT LOGGED ON
public IList<EncomendaModel> GetEncomendasList()
{
IList<EncomendaModel> encomendas= new List<EncomendaModel>();
//GET Encomenda Name && Number
string username = HttpContext.Request.Cookies.Get("nome").Value;
string query = "SELECT * FROM dbo.renland_encomenda AS child WHERE child.coordenad LIKE '" + username + "%'"; //Meter User.Identity.GetUserName(); aqui
DataSet table_encomendas = ExecuteQuery(query);
foreach (DataRow r in table_encomendas.Tables[0].Rows)
{
if (Convert.ToInt32(r[2]) == 1) //Se Encomenda esta ativa
{
EncomendaModel tEnco = new EncomendaModel();
string numEnco = r[0].ToString();
tEnco.NumEncomenda = r[1].ToString();
tEnco.NomeEncomenda = r[3].ToString();
encomendas.Add(tEnco);
}
}
query = "SELECT numero, ativa, prest_serv FROM dbo.renland_encomenda_patrimonio AS child WHERE child.coordenad LIKE '"+ username +"%'";
DataSet table_encomendas2 = ExecuteQuery(query);
foreach (DataRow r in table_encomendas2.Tables[0].Rows)
{
if (Convert.ToInt32(r[1]) == 1) //Se Encomenda esta ativa
{
EncomendaModel tEnco = new EncomendaModel();
string numEnco = r[0].ToString();
tEnco.NumEncomenda = r[0].ToString();
tEnco.NomeEncomenda = r[2].ToString();
encomendas.Add(tEnco);
}
}
return encomendas;
}
//GET ALL CONCELHOS
public IList<string> GetConcelhos()
{
IList<string> concelhos = new List<string>();
string query = "SELECT Concelho FROM dbo.Concelhos";
DataSet table = ExecuteQuery(query);
foreach(DataRow r in table.Tables[0].Rows)
{
concelhos.Add(r[0].ToString());
}
return concelhos;
}
//GET ALL LINHAS
public IList<Linhas> GetLinhas(string num)
{
IList<Linhas> tlinha = new List<Linhas>();
string query = "SELECT DISTINCT ID_LN FROM dbo.RENLAND_PLANOMANUTENCAOFAIXA AS child WHERE child.N_TENSAO LIKE '"+num+ "%' ORDER BY ID_LN ASC";
string query2 = "SELECT ID_LN, DESCR_LN FROM dbo.SEGMENTOS_RNT WHERE ID_LN LIKE '%' ORDER BY ID_LN ASC";
DataSet table = ExecuteQuery(query);
DataSet table2 = ExecuteQuery(query2);
foreach (DataRow r in table.Tables[0].Rows)
{
Linhas tl = new Linhas();
tl.NumLinha= r[0].ToString();
foreach (DataRow r2 in table2.Tables[0].Rows)
{
if (tl.NumLinha== r2[0].ToString())
{
tl.NomeLinha = r2[1].ToString();
break;
}
}
tlinha.Add(tl);
}
return tlinha;
}
//GET ALL GASODUTOS
public IList<Linhas> GetGasodutos()
{
IList<Linhas> tlinha = new List<Linhas>();
string query = "SELECT ID_GD, DEN_GD FROM dbo.Gasodutos_RNTGN ";
DataSet table = ExecuteQuery(query);
foreach (DataRow r in table.Tables[0].Rows)
{
Linhas tl = new Linhas();
tl.NumLinha = r[0].ToString();
tl.NomeLinha = r[1].ToString();
tlinha.Add(tl);
}
return tlinha;
}
}
}
Client Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Encomendas_WebFinal.Models;
using System.Web.Mvc;
namespace Encomendas_WebFinal.Models
{
public class ClientModel
{
private IList<EncomendaModel> listaEncomendas = new List<EncomendaModel>();
public IList<EncomendaModel> ListaEncomendas { get { return listaEncomendas; } set { listaEncomendas = value; } }
public PostEncomendaModel SelectedEncomenda { get; set; }
public Linhas SelectedLinha { get; set; }
public string SelectedConcelho { get; set; }
List<SelectListItem> _listEncomendas = new List<SelectListItem>();
public List<SelectListItem> ListEncomendas { get { return _listEncomendas; } set { _listEncomendas = value; } }
List<SelectListItem> _listLinha150 = new List<SelectListItem>();
public List<SelectListItem> ListLinha150 { get { return _listLinha150; } set { _listLinha150 = value; } }
List<SelectListItem> _listLinha220 = new List<SelectListItem>();
public List<SelectListItem> ListLinha220 { get { return _listLinha220; } set { _listLinha220 = value; } }
List<SelectListItem> _listLinha400 = new List<SelectListItem>();
public List<SelectListItem> ListLinha400 { get { return _listLinha400; } set { _listLinha400 = value; } }
List<SelectListItem> _listGasodutos = new List<SelectListItem>();
public List<SelectListItem> ListGasodutos { get { return _listGasodutos; } set { _listGasodutos = value; } }
List<SelectListItem> _listPatrimonios = new List<SelectListItem>();
public List<SelectListItem> ListPatrimonios { get { return _listPatrimonios; } set { _listPatrimonios = value; } }
List<SelectListItem> _listConcelhos = new List<SelectListItem>();
public List<SelectListItem> ListConcelhos { get { return _listConcelhos; } set { _listConcelhos = value; } }
}
}
PostEncomendaModel Model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace Encomendas_WebFinal.Models
{
public class PostEncomendaModel
{
//Not all data annotations are complete
[Required]
[Display(Name = "Encomenda")]
public string NumEncomenda { get; set; }
[Display(Name = "Nome da Encomenda")]
public String NomeEncomenda { get; set; }
[Required]
[Display(Name = "Linha")]
public Linhas Linha { get; set; }
[Required]
public string Data { get; set; }
public int Semana { get; set; }
[Display(Name = "Vãos")]
public String Vaos { get; set; }
private IList<String> _concelho = new List<String>();
[Display(Name = "Concelho")]
[Required]
public IList<String> Concelho { get { return _concelho; } set { _concelho = value; } }
public int TecnicoAvisoNum { get; set; }
public int EquipaCampoNum { get; set; }
private IList<String> _tecnicoAviso = new List<String>(3);
[Display(Name = "Tecnico de Aviso")]
public IList<String> TecnicoAviso { get { return _tecnicoAviso; } set { _tecnicoAviso = value; } }
private IList<String> _equipaCampo = new List<String>(3);
[Display(Name = "Equipa de Campo")]
public IList<String> EquipaCampo { get { return _equipaCampo; } set { _equipaCampo = value; } }
private IList<String> _tecnicoAvisoTel = new List<String>(3);
[Display(Name = "Telefone Tecnico")]
public IList<String> TecnicoAvisoTel { get { return _tecnicoAvisoTel; } set { _tecnicoAvisoTel = value; } }
private IList<String> _equipaCampoTel = new List<String>(3);
[Display(Name = "Telefone Equipa")]
public IList<String> EquipaCampoTel { get { return _equipaCampoTel; } set { _equipaCampoTel = value; } }
[Display(Name = "Email")]
public String Email { get; set; }
[Display(Name = "Observações")]
public String Observacoes { get; set; }
}
}
Your radios are like:
<input type="radio" name="selectedLinhaType" id="150KV"/> 150kV <br>
Where the name is selectedLinhaType. This name doesn't match up with any property on your view model, so any posted values will simply be discarded by the model binder. The name must match the name of the property you want the value to bind to. You could manually change the name attribute on these, but the better approach is to let Razor handle it:
#Html.RadioButtonFor(m => m.MyProperty, "foo")
Where MyProperty is the property you want to bind to the posted value to, and "foo" is the value this radio button should have.

ASP MVC knockout json nested foreach data binding

Sorry if this particular question has been asked already, I have been through countless similar questions but none that seem to relate with my problem.
I am fairly new to MVC Web API's and working with JavaScript/knockout.
View model script - QuestionItems.js
var SectionModel = function (data) {
var self = this;
self.SectionName = ko.observable(data.SectionName);
self.SectionNumber = ko.observable(data.SectionNumber);
self.Questions = ko.observableArray();
};
var questionnaireViewModel = function () {
self.sections = ko.observableArray();
self.error = ko.observable();
var itemsUri = '/api/QuestionnaireItems/';
var sectionsUri = '/api/QuestionnaireSections/';
function ajaxHelper(uri, method, data) {
self.error('');
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllQuestions() {
ajaxHelper(itemsUri, 'GET').done(function (data) {
for (var s = 0; s < self.sections.length; s++) {
// find all the questions for this section
var sectionQuestions = data.filter(function (item) {
return item.SectionName == self.sections[s].SectionName;
});
// add the questions to each section
self.sections.Questions(sectionQuestions);
}
});
}
function getAllSections() {
ajaxHelper(sectionsUri, 'GET').done(function (data) {
// map each data item to a SectionModel and store that in your main viewModel
var sectionsTemp = data.map(function (item) {
return new SectionModel(item);
});
self.sections(sectionsTemp);
});
}
getAllSections();
getAllQuestions();
};
ko.applyBindings(questionnaireViewModel);
And my view - Index.cshtml
#section scripts {
#Scripts.Render("~/bundles/QuestionItems")
}
<div class="col-lg-12">
<h1 class="page-header">SQA</h1>
<ul class="list-unstyled" data-bind="foreach: sections">
<li>
<div class="panel panel-default">
<div class="panel-heading">
<div><strong data-bind="text: SectionNumber"></strong>. <strong data-bind="text: SectionName"></strong></div>
</div>
<div class="panel-body">
<ul data-bind="foreach: Questions">
<li>
<span data-bind="text: QuestionNumber"></span>. <span data-bind="text: QuestionName"></span>
</li>
</ul>
</div>
</div>
</li>
</ul>
</div>
In the database I have a QuestionnaireItems table which stores all question details and a foreign key to the sections table to retrieve each questions related section :
QuestionnaireItems
And a QuestionnaireSections table which holds each sections name and order number :
QuestionnaireSections
I have managed to get the sections displaying, however the questions are not. If I pull through just the questions without matching them to their correct sections they display. I'm assuming this is a problem with the way the condition is set up but I am at a complete loss as to how I can fix this.
I have also tested the controllers in Postman and all the correct data is pulling through.
QuestionItemList.cs (DTO):
public class QuestionItemList
{
public int Id { get; set; }
public int SectionNumber { get; set; }
public string SectionName { get; set; }
public int QuestionNumber { get; set; }
public string QuestionName { get; set; }
}
SectionItemList.cs (DTO)
public class SectionItemList
{
public int Id { get; set; }
public int SectionNumber { get; set; }
public string SectionName { get; set; }
}
QuestionnaireItemsController:
public class QuestionnaireItemsController : ApiController
{
private SQAContext db = new SQAContext();
// GET: api/QuestionnaireItems
[HttpGet]
public IQueryable<QuestionItemList> GetItems()
{
var items = from a in db.QuestionnaireItems
select new QuestionItemList()
{
Id = a.PID,
SectionNumber = a.QuestionnaireSection.Number,
SectionName = a.QuestionnaireSection.Name,
QuestionNumber = a.Number,
QuestionName = a.Name
};
return items;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool QuestionnaireItemExists(int id)
{
return db.QuestionnaireItems.Count(e => e.PID == id) > 0;
}
}
QuestionnaireSectionsController:
public class QuestionnaireSectionsController : ApiController
{
private SQAContext db = new SQAContext();
// GET: api/QuestionnaireSections
[HttpGet]
public IQueryable<SectionItemList> GetSectionItems()
{
var items = from a in db.QuestionnaireSections
select new SectionItemList()
{
Id = a.PID,
SectionNumber = a.Number,
SectionName = a.Name
};
return items;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool QuestionnaireSectionExists(int id)
{
return db.QuestionnaireSections.Count(e => e.PID == id) > 0;
}
}

Populating dropdownlist based on previous selected item asp.net mvc

I am trying to populate a DropDownList based on the previous selected item. To achieve that, I have created three models
Country model:
[Key]
public int CountryId { get; set; }
public string CountryName { get; set; }
public virtual ICollection<State> States { get; set; }
State model:
[Key]
public int StateId { get; set; }
public string StateName { get; set; }
[ForeignKey("Country")]
public int CountryId { get; set; }
public virtual Country Country { get; set; }
public virtual ICollection<City> Citys { get; set; }
City model:
[Key]
public int CityId { get; set; }
public string CityName { get; set; }
[ForeignKey("State")]
public int StateId { get; set; }
public virtual State State { get; set; }
and here is my controller:
private ProjectContext db = new ProjectContext();
//
// GET: /CascadingDropdown/
public ActionResult Index()
{
ViewBag.CountryId = new SelectList(db.Countrys, "CountryId", "CountryName");
return View();
}
public JsonResult StateList(int Id)
{
var state = from s in db.States
where s.CountryId == Id
select s;
return Json(new SelectList(state.ToArray(), "StateId", "StateName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Citylist(int id)
{
var city = from c in db.Citys
where c.StateId == id
select c;
return Json(new SelectList(city.ToArray(), "CityId", "CityName"), JsonRequestBehavior.AllowGet);
}
public IList<State> Getstate(int CountryId)
{
return db.States.Where(m => m.CountryId == CountryId).ToList();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadClassesByCountryId(string CountryName)
{
var stateList = this.Getstate(Convert.ToInt32(CountryName));
var stateData = stateList.Select(m => new SelectListItem()
{
Text = m.StateName,
Value = m.CountryId.ToString(),
});
return Json(stateData, JsonRequestBehavior.AllowGet);
}
And then my script:
$(function () {
$('#Country').change(function () {
$.getJSON('/Cascading/StateList/' + $('#Country').val(), function (data) {
var items = '<option>Select a State</option>';
$.each(data, function (i, state) {
items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
});
$('#State').html(items);
});
});
$('#State').change(function () {
$.getJSON('/Cascading/Citylist/' + $('#State').val(), function (data) {
var items = '<option>Select a City</option>';
$.each(data, function (i, city) {
items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
});
$('#city').html(items);
});
});
});
Finally I display it with this view:
#model Test_restriction.DAL.ProjectContext
#using (Html.BeginForm())
{
#Html.DropDownList("Country", ViewBag.CountryId as SelectList, "Select a Country", new { id="Country" })<br />
<select id="State" name="state"></select><br />
<select id="city" name="City"></select><br />
}
#section js
{
<script src="~/Scripts/Testing.js" type="text/javascript"></script>
}
So I prefer to post all my code to be clear, now problem is that only the first DropDownList with countries is filled the two others DropDownList remain empty. Can someone help to find what is going wrong?
Thank you!
Try This
View
#model Test_restriction.DAL.CountryModel
<script type="text/javscript">
$(function(){
$('#ddlcountry').change(function () {
var sub = $('#ddlstate').val();
if (sub != null && sub != "") {
$('#ddlstate').html(' <option value="">--Select Topic--</option>');
$.ajax({
url: '/Cascading/StateList',
data: { id: sub },
type: 'post',
success: function (data) {
if (data != null && data != "") {
$.each(data, function (i, item) {
$("#ddlstate").append($("<option></option>").val(item.value).html(item.text));
});
}
else {
$('#ddlstate').html(' <option value="">--Select State--</option>');
}
}
});
}
else {
$('#ddlstate').html(' <option value="">--Select State--</option>');
}
});
});
</script>
#Html.DropDownListFor(m => m.subject_id, (SelectList)ViewBag.Countries, "--Select Country--", new { #Class = "form-control", id = "ddlcountry" })
<select id="ddlstate" name="state_id" class="form-control">
<option value="">--Select State--</option>
</select>
Controller
public ActionResult Index()
{
ViewBag.countries = new SelectList(db.Countrys, "CountryId", "CountryName");
return View();
}
public JsonResult StateList(int Id)
{
var state = (from s in db.States
where s.CountryId == Id
select s).ToList();
var list = state.Select(m => new { value = m..StateId, text = m.stateName });
return Json(list, JsonRequestBehavior.AllowGet);
}
Use same method for city dropdown..

Categories