getJSON data function doesnt work on IIS - c#

I have a pair of cascading drop down lists for Type & Sub Type. These work perfectly when testing in debug mode locally but once I publish to IIS the sub type list doesnt populate and is blank. I dont get any error messages.
I have tried this in IE9 & also Google Chrome V46 but get the same result.
The controllers are:
public ViewResult StartRA()
{
var user = User.Identity.Name;
string userName = user.Substring(7);
var creator = Peopledb.People.FirstOrDefault(x => x.Username == userName);
var creatorContractId = (int)Session["LoggedContractId"];
StartRiskAssessmentViewModel viewModel = new StartRiskAssessmentViewModel
{
RiskAssessment = new RiskAssessment(),
CreatorId = creator.PersonId,
CreatorContractId = creatorContractId,
Assessor = creator.FirstName + " " + creator.LastName,
Locations = Peopledb.Locations.Where(x => x.Dormant == false).OrderBy(x => x.LocationName).ToList(),
Types = db.Types.Where(x => x.Dormant == false).ToList(),
};
return View(viewModel);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult SubTypeList(int typeId)
{
var subTypes = db.SubTypes.Where(x => x.Dormant == false && x.TypeId == typeId).ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
subTypes,
"SubTypeId",
"SubTypeName"), JsonRequestBehavior.AllowGet
);
return View(subTypes);
}
And the Razor view is:
#model RACentral.ViewModels.StartRiskAssessmentViewModel
#{
ViewBag.Title = "Start RA";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<h3 class="col-md-offset-2">Type</h3>
<div class="form-group">
#Html.LabelFor(model => model.TypeId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TypeId, new SelectList(Model.Types, "TypeId", "TypeName", 0), "Please Select", new { #class = "form-control", #id = "Types" })
#Html.ValidationMessageFor(model => model.TypeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SubTypeId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select id="SubTypes" name="SubTypeId" class="form-control"></select>
#Html.ValidationMessageFor(model => model.SubTypeId, "", new { #class = "text-danger" })
</div>
</div>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-primary" /> #Html.ActionLink("Cancel", "IndexLoggedIn", "Home", null, new { #Class = "btn btn-danger" })
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$("#Types").change(function () {
$.getJSON('#Url.Action("SubTypeList","RiskAssessment")' {
var items = "<option>Please Select</option>";
$.each(data, function (i, subtype) {
items += "<option value='" + subtype.Value + "'>" + subtype.Text + "</option>";
});
$("#SubTypes").html(items);
});
});
</script>
}

You can do this using $.ajax and it might be easier for you to see what's happening
$(function () {
$("#Types").change(function () {
$.ajax({
type: "get", // can change to post easily
data: {typeId: $(this).val()}, // or this.value
url: "#Url.Action("SubTypeList", "RiskAssessment")" // use url helper here
}).done(function (data) {
var items = "<option>Please Select</option>";
$.each(data, function (i, subtype) {
items += "<option value='" + subtype.Value + "'>" + subtype.Text + "</option>";
});
$("#SubTypes").html(items);
});
});
});
using the url helper in your code was the right direction, you just needed to include your params also.
$.getJSON(
"#Url.Action("SubTypeList", "RiskAssessment")",
{ typeId: $(this).val() })
.done(function (data) {
var items = "<option>Please Select</option>";
$.each(data, function (i, subtype) {
items += "<option value='" + subtype.Value + "'>" + subtype.Text + "</option>";
});
$("#SubTypes").html(items);
});

Related

The record is getting inserted or updated in datatable after page refresh and also notify.js popup is not working after insert/update in ASP.NET MVC

I'm new to ASP.NET MVC and I have created CRUD operations using datatables.
I need some help for notify.js popup is not working after inserting and updating data and also the record is getting inserted or updated in datatable after page refresh in ASP.NET MVC.
This is my markup and code:
AddOrEdit.cshtml:
#model Asp.NETMVCCRUD.Models.Employee
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Employee", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
{
#Html.HiddenFor(model => model.EmployeeID)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { autocomplete = "off", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Position, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Position, new { htmlAttributes = new { autocomplete = "off", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Position)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Office, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Office, new { htmlAttributes = new { autocomplete = "off", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Office)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Age, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Age, new { htmlAttributes = new { autocomplete = "off", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Age)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Salary, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Salary, new { htmlAttributes = new { autocomplete = "off", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Salary)
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn btn-warning" />
</div>
}
Index.cshtml:
<script>
function SubmitForm(form) {
debugger
$.validator.unobtrusive.parse(form);
if ($(form).valid) {
$.ajax({
type: "post",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}
</script>
_Layout.cshtml:
<script src="~/Scripts/jquery-3.6.0.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery-ui-1.13.1.min.js"></script>
<script src="~/Scripts/notify.min.js"></script>
EmployeeController.cs:
[HttpPost]
public ActionResult AddOrEdit(Employee emp)
{
using (DBModel db = new DBModel())
{
if (emp.EmployeeID == 0)
{
db.Employees.Add(emp);
db.SaveChanges();
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
else
{
db.Entry(emp).State = EntityState.Modified;
db.SaveChanges();
return Json(new { success = true, message = "Updated Successfully" }, JsonRequestBehavior.AllowGet);
}
}
}

After I did update-package in the package manager my submit button has lost is functionality and does nothing

I have a registration form and there is two inputs for password and password confirmation. When I enter distinct values I wanted it to show the error message as 'Passwords should match' or something. So I googled it and found out that update-package should fix this problem. Then I applied this solution in order to fix my problem, now, neither my error message shows up nor my submit button works.
My Registration View:
<div class="container-fluid">
#using (Html.BeginForm("Register", "User", FormMethod.Post, new { #class = "col-12" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal p-3 m-3 w-100 d-flex flex-column align-items-center">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group w-100">
<label class="form-control-label col-md-12">Kullanıcı adı</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.kullaniciAdi, new { htmlAttributes = new { #class = "form-control", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.kullaniciAdi, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Firma adı</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.firmaAdi, new { htmlAttributes = new { #class = "form-control", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.firmaAdi, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Şifre</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.sifre, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "password" } })
#Html.ValidationMessageFor(model => model.User.sifre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Şifre tekrar</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.sifreTekrar, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "password" } })
#Html.ValidationMessageFor(model => model.User.sifre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">E-mail</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.mail, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "text" } })
#Html.ValidationMessageFor(model => model.User.mail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Telefon</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.telefon, new { htmlAttributes = new { #class = "form-control", #type = "text", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.telefon, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Ülkeniz</label>
#Html.EditorFor(model => model.Address.ulkeID, new { htmlAttributes = new { #class = "form-control", #type = "text", #readonly="readonly", #Value="Türkiye" } })
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Bulunduğunuz il</label>
<select class="form-control col-md-12" name="Address.sehirID" id="il" required></select>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Bulunduğunuz ilçe</label>
<select class="form-control col-md-12" name="Address.ilceID" id="ilce" disabled required>
<option>Bir İl Seçiniz</option>
</select>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Açık adresiniz</label>
<div class="col-md-12">
#Html.EditorFor(model => model.Address.acikAdres, new { htmlAttributes = new { #class = "form-control", #type = "text", #required = "required" } })
#Html.ValidationMessageFor(model => model.Address.acikAdres, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Oluşturulma Tarihi</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.olusturulmaTarihi, new { htmlAttributes = new { #class = "form-control", #type = "text", #readonly="readonly", #Value=sqlFormat } })
#Html.ValidationMessageFor(model => model.Address.acikAdres, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<div class="col-md-offset-2 col-md-12">
<input type="submit" value="Kaydol" class="btn btn-success" />
</div>
</div>
</div>
}
</div>
Register Action:
[HttpPost]
public ActionResult Register(RegisterVM model)
{
tblKullanici user = null;
tblAdres address = null;
if(model != null)
{
db = new DatabaseContext();
user = model.User;
address = model.Address;
db.tblKullanici.Add(user);
db.tblAdres.Add(address);
db.SaveChanges();
if (db.SaveChanges() > 0)
{
Session["login"] = model.User;
return RedirectToAction("Index", "App");
}
}
ViewBag.Message = "Kayıt işlemi sırasında hata oluştu!";
return View(model);
}
jQuery
<script>
// ajax call to bring district and city info dynamically according to the city value
$(function () {
$.ajaxSetup({
type: "post",
url: "/User/IlIlce",// target
dataType: "json"
});
$.extend({
ilGetir: function () {
$.ajax({
//sending data
data: { "tip": "ilGetir" },
success: function (sonuc) {
//check result if ok then append it to selectlist
if (sonuc.ok) {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#il").append(optionhtml);
});
} else {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#il").append(optionhtml);
$("body").append(optionhtml);
});
}
}
});
},
ilceGetir: function (cityID) {
$.ajax({
// then we get the districts with cityID
data: { "ilID": cityID, "tip": "ilceGetir" },
success: function (sonuc) {
// deleting records
$("#ilce option").remove();
if (sonuc.ok) {
// disabled to false
$("#ilce").prop("disabled", false);
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#ilce").append(optionhtml);
});
} else {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#ilce").append(optionhtml);
});
}
}
});
}
});
// invoke ilGetir to get city values
$.ilGetir();
// on change in city value
$("#il").on("change", function () {
// we get the id of selected value
var cityID = $(this).val();
// and pass it to the ilceGetir function to get the districts
$.ilceGetir(cityID);
});
});
</script>
and the method that ajax call goes:
public JsonResult IlIlce(int? ilID, string tip)
{
db = new DatabaseContext();
List<SelectListItem> sonuc = new List<SelectListItem>();
bool isSuccessful = true;
try
{
switch (tip)
{
case "ilGetir":
// we assign the city values in db to sonuc(result) variable
foreach (var sehir in db.tblSehir.ToList())
{
sonuc.Add(new SelectListItem
{
Text = sehir.sehirAdi,
Value = sehir.sehirID.ToString()
});
}
break;
case "ilceGetir":
// we will fetch districts with sehirID(cityID)
foreach (var ilce in db.tblİlce.Where(il => il.bagliOlduguSehirID == ilID).ToList())
{
sonuc.Add(new SelectListItem
{
Text = ilce.ilceAdi,
Value = ilce.ilceID.ToString()
});
}
break;
default:
break;
}
}
catch (Exception e)
{
// if we encounter an error
isSuccessful = false;
sonuc = new List<SelectListItem>();
sonuc.Add(new SelectListItem
{
Text = e.Message,
Value = "Default"
});
}
// i return the results as json
return Json(new { ok = isSuccessful, text = sonuc });
}
ilce means: district
sehir/il both means: city
sifre: password
kullaniciAdi: username
telefon: phone number
ulke: country
ilGetir : fetch city
ilceGetir: fetch district
kullanici: user
adres: address
sonuc: result
tip: type

Asp.net mvc crud operation datepicker

Hi i have simple MVC with crud operation the problem starting always if i try to put a datepicker (that i did not get it either work), in that field
<div class="form-group">
#Html.LabelFor(model => model.Age, new { #class = "control-label" })
#Html.EditorFor(model => model.Age, new { htmlAttributes = new { #class = "form-control" } })
</div>
The datepicker is from https://jqueryui.com/datepicker/ the problem is that the field model.Age is part of a form with class"form-control" so i must add second class to give to the datepicker?
in my index file i have a lot of scripts look the script that for datepicker`
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: 'Fill Employee Details',
height: 500,
width: 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function datepicker (){
$(".example").datepicker();
};
`
Is below from another function the question is on the datepicker function on .example if i add a new class same and call from the model.age isn't working the datepicker,
and the worst scenario is that the application after of several tries lost the pagination and i lost the original view of the site.
All Index
#{
ViewBag.Title = "Employee List";
}
<h2>Employee CRUD Operations</h2>
<a class="btn btn-success" style="margin-bottom:10px" onclick="PopupForm('#Url.Action(" AddOrEdit","Employee")')"><i class="fa fa-plus"></i> Add New</a>
<table id="employeeTable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
<th></th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
#section scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#employeeTable").DataTable({
"ajax": {
"url": "/Employee/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name" },
{ "data": "Position" },
{ "data": "Office" },
{ "data": "Age" },
{ "data": "Salary" },
{"data":"EmployeeID" , "render" : function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit","Employee")/" + data + "')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete("+data+")><i class='fa fa-trash'></i> Delete</a>";
},
"orderable": false,
"searchable":false,
"width":"150px"
}
],
"language": {
"emptyTable" : "No data found, Please click on <b>Add New</b> Button"
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: 'Fill Employee Details',
height: 500,
width: 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function datepicker (){
$(".example").datepicker();
};
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if($(form).valid()){
$.ajax({
type : "POST",
url : form.action,
data : $(form).serialize(),
success : function (data) {
if(data.success)
{
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,{
globalPosition :"top center",
className : "success"
})
}
}
});
}
return false;
}
function Delete(id) {
if(confirm('Are You Sure to Delete this Employee Record ?'))
{
$.ajax({
type: "POST",
url: '#Url.Action("Delete","Employee")/' + id,
success: function (data) {
if (data.success)
{
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
}
</script>
}
and the all addoredit model that includes the form and the model.age.
#model Asp.NETMVCCRUD.Models.Employee
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Employee", FormMethod.Post, new {onsubmit = "return SubmitForm(this)" }))
{
#Html.HiddenFor(model => model.EmployeeID)
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label" })
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Position, new { #class = "control-label" })
#Html.EditorFor(model => model.Position, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Position)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Office, new { #class = "control-label" })
#Html.EditorFor(model => model.Office, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Age, new { #class = "control-label" })
#Html.EditorFor(model => model.Age, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Salary, new { #class = "control-label" })
<div class="input-group">
<span class="input-group-addon">$</span>
#Html.EditorFor(model => model.Salary, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn" />
</div>
}
I want to restore my site on the original view, and the second is that i want a datepicker on the mode.age textbox!
I see that you don't call your function datepicker()!, you have to call it after making sure that the dialog opened, and its content displayed.
Based on used jquery library to open the form in popup (dialog), you will use the event of after displaying and call your function datepicker() in its handler.
For adding multiple class to the same element you can do the following
#Html.EditorFor(model => model.Age, new { htmlAttributes = new { #class = "form-control example" } })
I hope this help you.

How to synchronize two DropDownList elements in MVC5?

I have categories and subcategories as model. And each category includes many subcategories as you may have guessed. The point is that I have a view, and in my view I have a code segment like this one:
<div class="form-group">
#Html.LabelFor(model => model.CategoryID, "Category", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CategoryID", null, "Please select a category", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CategoryID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SubcategoryID, "Subcategory", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("SubcategoryID", null, "Please select a subcategory", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SubcategoryID, "", new { #class = "text-danger" })
</div>
</div>
Then, in my controller, I have two ViewBag objects, which populate my SelectList objects:
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
ViewBag.SubcategoryID = new SelectList(db.Subcategories, "SubcategoryID", "SubcategoryName");
Then I wrote some AJAX code, in order to make the values of the DropDownList elements to synchronize. I have the following action and JS code.
[AllowAnonymous]
public JsonResult GetSubcategories(int id)
{
var results = db.Subcategories.Where(s => s.CategoryID == id).Select(x => new { id = x.SubcategoryID, value = x.SubcategoryName }).ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
JavaScript code with the AJAX call:
$("#CategoryID").change(function () {
$("#SubcategoryID").empty();
$.ajax({
type: 'POST',
url: '/Account/GetSubcategories',
dataType: 'json',
data: { id: $("#CategoryID").val() },
success: function (subcategories) {
$.each(subcategories, function (i, subcategory) {
$("#SubcategoryID").append('<option value="' + subcategory.value + '">' + subcategory.value + '</option>');
});
},
error: function (ex) {
console.log('Failed to retrieve subcategories! ' + ex);
}
});
return false;
});
The point is that, it synchronized the DropDownLists, so whenever I select a category, I only shows subcategories for that selected category. But, I'm not able to submit my form now, whenever I press submit, I get an error message saying that the selected value is not a valid Subcategory. How can I fix it?
EDIT:
When I did some digging with the developer tools, I saw that for my Categories, for the value part I have numbers, which are their corresponding id in the database, but now for my Subcategories for the value part I get a text, meaning the name of the Subcategory.
This
$("#SubcategoryID").append('<option value="' + subcategory.value + '">' + subcategory.value + '</option>');
should be
$("#SubcategoryID").append('<option value="' + subcategory.id + '">' + subcategory.value + '</option>');

Textarea won't save to database using jQuery

I'm trying to dynamically add form fields using jQuery and save the input in my database. All of the fields are saving to the database just fine except for the textarea. I'm not sure what the issue is.
View
#model DailyTaskList.Models.DTL_Tasks
#{
var db = new DailyTaskList.Models.DailyTaskListEntities();
var options = db.DTL_UserOptions.Where(u => u.UserProfile.UserId == WebMatrix.WebData.WebSecurity.CurrentUserId);
var priority = db.DTL_Tasks.Select(p => p.Priority).FirstOrDefault();
var customerNames = db.DTL_Customers.Select(c => c.CustomerName);
var userSelectedTasks = options.Select(o => o.DTL_TaskTypes);
SelectList userSelectedTasksList = new SelectList(userSelectedTasks);
var priorityListItems = new SelectListItem[] {
new SelectListItem(){ Text="", Value="0" },
new SelectListItem(){ Text="Low", Value="1" },
new SelectListItem(){ Text="Medium", Value="2" },
new SelectListItem(){ Text="High", Value="3" },
new SelectListItem(){ Text="Highest", Value="4" }
};
using (Html.BeginForm("Index", "NewTask", FormMethod.Post, new { id = "new-task-form" })) {
#Html.ValidationSummary(true)
// Original form fields
<div class="new-task-form-wrapper">
<div class="form-group">
<label>Customer:</label>
#Html.DropDownListFor(model => model.CustomerId, new SelectList(db.DTL_Customers, "CustomerId", "CustomerName"), new { #class = "form-control", id = "Customer_0" })
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-10">
<label>Activity:</label>
#Html.DropDownListFor(model => model.TaskTypeId, new SelectList(userSelectedTasks, "TaskTypeId", "TaskName"), new { #class = "form-control", id = "Activity_0" })
</div>
<div class="col-sm-2">
<label>Priority:</label>
#Html.DropDownListFor(model => model.Priority, priorityListItems, new { #class = "form-control", id = "Priority_0" })
</div>
</div>
</div>
<div class="form-group">
<label>Title:</label>
#Html.TextBoxFor(model => model.TaskTitle, new { #class = "form-control", id = "Title_0" })
</div>
<div class="form-group description">
<label>Description:</label>
#Html.TextAreaFor(model => model.TaskDescription, new { #class = "form-control", id = "Description_0" })
</div>
</div>
// Additional form fields
<div id="additional-form-fields_0" class="hide new-task-form-wrapper">
<div class="form-group">
<label>Customer:</label>
#Html.DropDownListFor(model => model.CustomerId, new SelectList(db.DTL_Customers, "CustomerId", "CustomerName"), new { #class = "form-control", id = "Customer_1" })
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-10">
<label>Activity:</label>
#Html.DropDownListFor(model => model.TaskTypeId, new SelectList(userSelectedTasks, "TaskTypeId", "TaskName"), new { #class = "form-control", id = "Activity_1" })
</div>
<div class="col-sm-2">
<label>Priority:</label>
#Html.DropDownListFor(model => model.Priority, priorityListItems, new { #class = "form-control", id = "Priority_1" })
</div>
</div>
</div>
<div class="form-group">
<label>Title:</label>
#Html.TextBoxFor(model => model.TaskTitle, new { #class = "form-control", id = "Title_1" })
</div>
<div class="form-group description">
<label>Description:</label>
#Html.TextAreaFor(model => model.TaskDescription, new { #class = "form-control", id = "Description_1" })
</div>
</div>
// Form controls
<div class="form-group">
<button type="submit" class="btn btn-default" value="Create">Submit</button>
<div class="btn btn-default" id="addnew">+</div>
#*<div class="btn btn-default" id="remove">-</div>*#
</div>
}
}
Script
$(document).ready(function () {
CKEDITOR.replace('Description_0');
var counter = 0;
var additionalFormFields = $("#additional-form-fields_" + String(counter));
var customerInput = $("#Customer_1"),
activityInput = $("#Activity_1"),
priorityInput = $("#Priority_1"),
titleInput = $("#Title_1"),
descriptionInput = $("#Description_1");
$('#addnew').click(function () {
if (counter == 0) {
additionalFormFields.removeClass("hide");
}
else {
var newFormFields = additionalFormFields.clone();
additionalFormFields.after(newFormFields);
}
additionalFormFields.attr("id", "additional-form-fields_" + String(counter));
customerInput.attr("id", "Customer_" + String(counter + 1));
customerInput.attr("name", "CustomerId_" + String(counter));
activityInput.attr("id", "Activity_" + String(counter + 1));
activityInput.attr("name", "TaskTypeId_" + String(counter));
priorityInput.attr("id", "Priority_" + String(counter + 1));
priorityInput.attr("name", "Priority_" + String(counter));
titleInput.attr("id", "Title_" + String(counter + 1));
titleInput.attr("name", "TaskTitle_" + String(counter));
descriptionInput.attr("id", "Description_" + String(counter + 1));
descriptionInput.attr("name", "DescriptionId_" + String(counter));
counter++;
return false;
});
$('#new-task-form').on('submit', function (e) {
e.preventDefault();
var data = [];
$.each($(".new-task-form-wrapper"), function (i, o) {
data.push({
CustomerId: $(this).find("select[name^='CustomerId']").val(),
TaskTypeId: $(this).find("select[name^='TaskTypeId']").val(),
Priority: $(this).find("select[name^='Priority']").val(),
TaskTitle: $(this).find("input[name^='TaskTitle']").val(),
TaskDescription: $(this).find("textarea[name^='DescriptionId']").val()
});
});
$.ajax({
url: 'NewTask/Index',
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data)
});
});
});
Well, your text area's name is TaskDescription so the more appropriate selector would be:
TaskDescription: $(this).find("textarea[name^='TaskDescription']").val()

Categories

Resources