Ajax.Get Call not firing in Partial Views when master page loads - c#

I am trying to set a master page Employee Qualifications, this master page will include other views suck as work experience, employee skills, education.
In each partial view i have an ajax get method that brings the data and returns on success to render the partial view. the problem is that the method LoadWorkExperiences(); never gets fired when i navigate to the master page and hence the data is never loaded in view.
I am doing it this way because i want to open an edit popup window by clicking of the button. there for loading directly to master page is not my option.
Thanks for your help.
I tried calling "HumanResourse/WorkExperience/DisplayWorkExperience/15" and it also does not fire the Ajax call.
the Master View cshtml HERE.
#{
ViewBag.Title = "Display";
Layout = "~/Areas/HumanResourse/Views/Shared/_LayoutHRUB.cshtml";
int EmpId = ViewBag.EmployeeId;
}
<h2>Qualifications</h2>
<div>
<p>Work Experience</p>
#Html.Action("DisplayWorkExperience", "WorkExperience", new { id = EmpId })
</div>
<div>
<p>Education</p>
#Html.Action("DisplayEducation", "Education", new { id = EmpId })
</div>
the sub view code DisplayWorkExperience HERE.
#model SaaS.Areas.HumanResourse.Models.HR_Emp_WorkExperience_ViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<title>DisplayWorkExperience</title>
</head>
<body>
<input class="hidden" id="EmpId" value="#ViewBag.EmployeeId" />
<div class="container">
<label>Work Experiences</label>
Add New Work Experience <br /><br />
<table id="tblWorkExperience" class="table table-striped">
<thead>
<tr>
<th>Company</th>
<th>Position</th>
<th>From</th>
<th>To</th>
<th>Comment</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
#*Create A Popup Modal With Registration Form For Add Or Edit Student Record*#
<div class="modal fade" id="MyModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h4 id="ModalTitle"></h4>
</div>
<div class="modal-body">
<form id="form">
<fieldset id="SubmitForm">
#Html.HiddenFor(m => m.HR_Emp_WorkExperienceId, new { #id = "WorkExperienceId" })
<div class="form-group">
#Html.TextBoxFor(m => m.CompanyName, new { #id = "CompName", #class = "form-control", #placeholder = "Company Name*" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.Position, new { #id = "Position", #class = "form-control", #placeholder = "Position*" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.From, new { #id = "DateFrom", #class = "form-control" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.To, new { #id = "DateTo", #class = "form-control" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.Comment, new { #id = "Position", #class = "form-control", #placeholder = "Comment" })
</div>
<div class="form-group">
Save
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
#section scripts
{
<script type="text/javascript">
$(Document).ready(function () {
$("#LoadingStatus").html("Loading....");
LoadWorkExperiences();
});
//Start LoadWorkExperiences
function LoadWorkExperiences() {
$("#tblWorkExperience tbody tr").remove();
var EmpId = $("#EmpId").val();
$.ajax({
type: "POST",
url: '#Url.Action("GetEmpWorkExperiences", "WorkExperience", new {id = "ID"})'.replace("ID", EmpId),
dataType: "json",
success: function (data) {
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='h5'>" + item.CompanyName + "</td>"
+ "<td class='h5'>" + item.Position + "</td>"
+ "<td class='h5'>" + item.From + "</td>"
+ "<td class='h5'>" + item.To + "</td>"
+ "<td class='h5'>" + item.Comment + "</td>"
+ "<td>" + "<a href='#' class='btn btn-warning' onclick='EditWorkExperience(" + item.HR_Emp_WorkExperienceId + ")' ><span class='glyphicon glyphicon-edit'></span></a>" + "</td >"
+ "<td>" + "<a href='#' class='btn btn-danger' onclick='DeleteWorkExperience(" + item.HR_Emp_WorkExperienceId + ")'><span class='glyphicon glyphicon-trash'></span></a>" + "</td>"
+ "</tr>";
$("#tblWorkExperience tbody").append(rows);
$("#LoadingStatus").html(" ");
});
},
error: function (ex) {
var r = jQuery.parseJSON(Response.text);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
}
});
};
</script>
}
The Controller Code HERE.
public class WorkExperienceController : Controller
{
ApplicationDbContext Db;
public WorkExperienceController()
{
Db = new ApplicationDbContext();
}
// GET: HumanResourse/WorkExperience
public ActionResult Index()
{
return View();
}
public ActionResult DisplayWorkExperience(int? id)
{
TempData["EmployeeId"] = id;
ViewBag.EmployeeId = id;
return View();
}
public JsonResult GetEmpWorkExperiences(int? id)
{
if (id == null)
{
throw new HttpException(404, "Bad Request");
}
var EmpQualification = Db.HR_Emp_Qualifications.SingleOrDefault(p => p.HR_Emp_QualificationId == id);
if (EmpQualification == null)
{
throw new HttpException(404, "Not Found");
}
List<HR_Emp_WorkExperience_ViewModel> EmpWorkExpList = EmpQualification.HR_Emp_WorkExperiences.Select(x => new HR_Emp_WorkExperience_ViewModel
{
HR_Emp_WorkExperienceId = x.HR_Emp_WorkExperienceId,
CompanyName = x.CompanyName,
Position = x.Position,
From = x.From,
To = x.To,
Comment = x.Comment
}).ToList();
return Json(EmpWorkExpList, JsonRequestBehavior.AllowGet);
}
}
i am getting now this error
Failed to construct 'Document': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

I think you can rework what you have here, and it should work, like so:
Index.cshtml:
#{
ViewBag.Title = "Display";
Layout = "~/Areas/HumanResourse/Views/Shared/_LayoutHRUB.cshtml";
int EmpId = ViewBag.EmployeeId;
}
#section scripts
{
<script>
$(function () {
$("#LoadingStatus").html("Loading....");
LoadWorkExperiences();
});
//Start LoadWorkExperiences
function LoadWorkExperiences() {
$("#tblWorkExperience tbody tr").remove();
var EmpId = $("#EmpId").val();
$.ajax({
type: "POST",
url: '#Url.Action("GetEmpWorkExperiences", "WorkExperience")/' + EmpId,
dataType: "json",
success: function (data) {
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='h5'>" + item.CompanyName + "</td>"
+ "<td class='h5'>" + item.Position + "</td>"
+ "<td class='h5'>" + item.From + "</td>"
+ "<td class='h5'>" + item.To + "</td>"
+ "<td class='h5'>" + item.Comment + "</td>"
+ "<td>" + "<a href='#' class='btn btn-warning' onclick='EditWorkExperience(" + item.HR_Emp_WorkExperienceId + ")' ><span class='glyphicon glyphicon-edit'></span></a>" + "</td >"
+ "<td>" + "<a href='#' class='btn btn-danger' onclick='DeleteWorkExperience(" + item.HR_Emp_WorkExperienceId + ")'><span class='glyphicon glyphicon-trash'></span></a>" + "</td>"
+ "</tr>";
$("#tblWorkExperience tbody").append(rows);
$("#LoadingStatus").html(" ");
});
},
error: function (ex) {
var r = jQuery.parseJSON(Response.text);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
}
});
};
</script>
}
<h2>Qualifications</h2>
<div>
<p>Work Experience</p>
#Html.Action("DisplayWorkExperience", "WorkExperience", new { id = EmpId })
</div>
<div>
<p>Education</p>
#Html.Action("DisplayEducation", "Education", new { id = EmpId })
</div>
DisplayWorkExperience.cshtml (displayed as a partial view):
<input class="hidden" id="EmpId" value="#ViewBag.EmployeeId" />
<div class="container">
<label>Work Experiences</label>
Add New Work Experience <br /><br />
<table id="tblWorkExperience" class="table table-striped">
<thead>
<tr>
<th>Company</th>
<th>Position</th>
<th>From</th>
<th>To</th>
<th>Comment</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
#*Create A Popup Modal With Registration Form For Add Or Edit Student Record*#
<div class="modal fade" id="MyModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h4 id="ModalTitle"></h4>
</div>
<div class="modal-body">
<form id="form">
<fieldset id="SubmitForm">
#Html.HiddenFor(m => m.HR_Emp_WorkExperienceId, new { #id = "WorkExperienceId" })
<div class="form-group">
#Html.TextBoxFor(m => m.CompanyName, new { #id = "CompName", #class = "form-control", #placeholder = "Company Name*" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.Position, new { #id = "Position", #class = "form-control", #placeholder = "Position*" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.From, new { #id = "DateFrom", #class = "form-control" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.To, new { #id = "DateTo", #class = "form-control" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.Comment, new { #id = "Position", #class = "form-control", #placeholder = "Comment" })
</div>
<div class="form-group">
Save
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
With a few changes to the controller:
public class WorkExperienceController : Controller
{
// ... the rest of your code
[ChildActionOnly] // An attribute which will prevent this action from being called by anything but Html.Action()
public ActionResult DisplayWorkExperience(int? id)
{
TempData["EmployeeId"] = id;
ViewBag.EmployeeId = id;
return PartialView(); // this needs to return a partial view
}
}
This is untested, but if I'm understanding the end result you're after, this should work. Basically:
Move the #section to the full view, Index.cshtml, so that it actually gets rendered. It doesn't matter where in the page you have that - I prefer to put #section calls at the top of the view, but it doesn't affect where that code is injected into the layout.
Change the return type of DisplayWorkExperience to PartialViewResult, so that it doesn't try to render the layout
Add the ChildActionOnlyAttribute to DisplayWorkExperience (optional) - this is purely to indicate that DisplayWorkExperience is only for rendering an embedded view, and will throw an exception if an attempt is made to navigate to that action.
From there, the jQuery code you have should work as I think you intended.

Related

Text fields not updating with user detail from VIEW button

Im writing an application that connects to an API and allows users to do CRUD operations
In the Frontend.
I Have a button on each row in a table that is called 'View' once clicked, it should copy the info from the row that it was clicked on, into text fields for updating user details.
Table with button
Update Filed after click
I have a debugger under the FillStudentInfo: function (studentId) {} Method and when I debug i can see that the correct record is in the json response, but it doestn seem to add it to the text fields for some reason
Debugger
As you can see, the update field is blank.
StudentSummary.js
var StudentSummaryManager = {
GetAllStudents: function () {
var obj = "";
var serviceUrl = "https://localhost:5001/api/student";
AjaxManager.GetAPI(serviceUrl, onSuccess, onFailed);
function onSuccess(jsonData) {
obj = jsonData;
}
function onFailed(error) {
alert(error.statusText);
}
return obj;
},
GetStudentById: function (studentId) {
var obj = "";
var serviceUrl = "https://localhost:5001/api/student/" + studentId;
AjaxManager.GetAPI(serviceUrl, onSuccess, onFailed);
function onSuccess(jsonData) {
obj = jsonData;
}
function onFailed(error) {
alert(error.statusText);
}
return obj;
}
};
var StudentSummaryHelper = {
InitStudentSummary: function () {
StudentSummaryHelper.LoadStudent();
},
LoadStudent: function () {
$("#Table tbody tr").remove();
var studentList = StudentSummaryManager.GetAllStudents();
$.each(studentList, function (i, item) {
var rows = "<tr>" +
"<td>" + item.StudentId + "</td>" +
"<td>" + item.FirstName + "</td>" +
"<td>" + item.LastName + "</td>" +
"<td>" + item.DateofEnrollment + "</td>" +
"<td>" + item.Active + "</td>" +
"<td><button class='btn btn-info' onClick='StudentSummaryHelper.FillStudentInfo(" + item.StudentId + ")'>View</button></td>" +
"</tr>";
$("#Table tbody").append(rows);
});
},
FillStudentInfo: function (studentId) {
debugger;
var studInfo = StudentSummaryManager.GetStudentById(studentId);
$("#btnSave").text("Update");
$("#divDetails").show();
$("#divSummary").hide();
$("#txtStudentFirstName").val(studInfo.FirstName);
$("#txtStudentLastName").val(studInfo.LastName);
$("#txtStudentDate").val(studInfo.DateofEnrollment);
$("#txtStudentActive").val(studInfo.Active);
}
}
StudentSummary.cshtml
<script src="~/js/Student/StudentSummary.js"></script>
<div class="row">
<div class="col-12">
<h4>Summary of all students</h4>
</div>
<div class="col-md-12">
<button class="btn btn-success" id="btnAdd">Add Student</button>
<table class="table table-striped" id="Table">
<thead>
<tr>
<th>StudentId</th>
<th>FirstName</th>
<th>LastName</th>
<th>DateofEnrollment</th>
<th>Active</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
StudentDetails.js
var StudentDetailsManager = {
SaveStudent: function () {
var obj = StudentDetailsHelper.CreateStudObj();
var objStudent = JSON.stringify(obj);
var serviceUrl = "https://localhost:5001/api/student/AddStudent"
AjaxManager.PostApi(serviceUrl, objStudent, onSuccess, onFailed)
function onSuccess(jsonData) {
if (jsonData.FirstName !== "") {
$("#divDetails").hide();
$("#divSummary").show();
StudentSummaryHelper.LoadStudent();
alert("Saved Successfully");
}
else {
alert(jsonData);
}
}
function onFailed(error) {
alert(error.statusText);
}
}
};
var StudentDetailsHelper = {
InitStudentDetails: function () {
$("#btnAdd").click(function () {
$("btnSave").text("Save");
$("#divDetails").show();
$("#divSummary").hide();
StudentDetailsHelper.ClearForms();
});
$("#btnSave").click(function () {
StudentDetailsManager.SaveStudent();
});
},
CreateStudObj: function () {
debugger;
var obj = new Object();
obj.FirstName = $("#txtStudentFirstName").val();
obj.LastName = $("#txtStudentLastName").val();
obj.DateofEnrollment = $("#txtStudentDate").val();
if ($("#txtStudentActive").is(":checked")) {
obj.Active = "true"
} else {
obj.Active = "false"
}
return obj;
},
ClearForms() {
$("#txtStudentFirstName").val("");
$("#txtStudentLastName").val("");
$("#txtStudentDate").val("");
$("txtStudentActive").val(null);
}
}
StudentDetails.cshtml:
<script src="~/js/Student/StudentDetails.js"></script>
<div class="col-6">
<div class="form-group">
<input type="hidden" id="hdnStudentId" value="0" />
<label class="col-md-3 col-xl control-label" for="txtStudentFirstName">First Name:</label>
<div class="col-md-7 col-xs-7">
<input type="text" class="form-control" id="txtStudentFirstName" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xl control-label" for="txtStudentLastName">Last Name:</label>
<div class="col-md-7 col-xs-7">
<input type="text" class="form-control" id="txtStudentLastName" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xl control-label" for="txtStudentDate">Enrollment Date:</label>
<div class="col-md-7 col-xs-7">
<input type="date" class="form-control" id="txtStudentDate" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xl control-label" for="txtStudentActive">Active:</label>
<div class="col-md-7 col-xs-7">
<input type="checkbox" class="form-control" id="txtStudentActive" />
</div>
</div>
<div class="row">
<div class="spacer5"></div>
<div class="col-md-12 col-xs-12">
<ul class="list-group">
<li class="list-group-item centerAlign">
<button id="btnSave" class="btn btn-success" type="button">Save</button>
</li>
</ul>
</div>
</div>
</div>
So for some reason in the FillStudentInfo: function (studentId) {}
Method I needed to ad a $.each even though the response was only 1 Student.
Heres the fixed method that works:
FillStudentInfo: function (studentId) {
debugger;
var studInfo = StudentSummaryManager.GetStudentById(studentId);
$("#btnSave").text("Update");
$("#divDetails").show();
$("#divSummary").hide();
$.each(studInfo, function (i, studInfo) {
$("#txtStudentFirstName").val(studInfo.FirstName);
$("#txtStudentLastName").val(studInfo.LastName);
$("#txtStudentDate").val(studInfo.DateofEnrollment);
$("#txtStudentActive").val(studInfo.Active);
});
}

How to pass external object list and form object in ajax to mvc controller

I am going to pass external object list with form-data in submitHandler section. When i am passing form object only it is working properly. but i want to add list of object to that ajax post request.
JS
submitHandler: function (e) {
$(".loader-showhide").show();
var contacts = [
{ name: 'test 1', mobile: '11111111' },
{ name: 'test 2', mobile: '22222222' }
];
var dataToPost = JSON.stringify({ contacts: contacts });
var form = $(e);
form.find(":submit").attr("disabled", true);
$.ajax(form.attr("action"),
{
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: 'JSON',
data: { model: $(form).serialize(), contacts: dataToPost },
cache: false,
success(data) {
$(".loader-showhide").hide();
$("#myModal").modal('hide');
var table = $('#dt_account').DataTable();
table.ajax.reload();
toastr.success('Successfully added.');
$('#submitBtn').prop("disabled", false);
},
error(xhr) {
}
});
}
Controller
[HttpPost]
public ActionResult Create(ActivityViewModel model, List<Contact> contacts)
{
try
{
int result = 0;
return Json(new { StatusCode = result });
}
catch (Exception ex)
{
throw ex;
}
}
Object
public class Contact
{
public string Name { get; set; }
public string Mobile { get; set; }
}
Here is my form, I used jquery datatable and jquery form submit with submit handler.
<form action="#Url.Action("Create", "Activity")" id="account-form" method="POST" novalidate="novalidate" enctype="multipart/form-data">
<div class="form-blocker-wrap">
#Html.HiddenFor(o => o.Id)
<div class="card-block row">
<div class="col-lg-12">
<div class="scroller bottom-box px-3">
<div class="row">
<div class="col-lg-12 py-5 px-4 border-right">
<div class="col-md-6 form-group">
<label asp-for="Name">Activity Name</label>
#Html.TextBoxFor(o => o.Name, new { maxlength = 100, placeholder = "Campaign Name", #class = "form-control", required = "true" })
</div>
<div class="col-md-3 form-group">
<label asp-for="StartDateTime">Start Date</label>
#Html.TextBoxFor(o => o.StartDateTime, new { type = "date", maxlength = 100, placeholder = "Start Date", #class = "form-control", required = "true" })
</div>
<div class="col-md-3 form-group">
<label asp-for="EndDateTime">End Date</label>
#Html.TextBoxFor(o => o.EndDateTime, new { type = "date", maxlength = 100, placeholder = "End Date", #class = "form-control", required = "true" })
</div>
</div>
<div class="col-lg-12 py-5 px-4 border-right">
<div class="col-md-6 form-group">
<label asp-for="ContactType">Select Method</label><br />
#Html.DropDownListFor(o => o.ContactType, (IEnumerable<SelectListItem>)Model.ContactList, new { maxlength = 100, placeholder = "Campaign Name", #class = "form-control", #onchange = "ChangeMethod(this)", required = "true" })
</div>
</div>
<div class="col-lg-12 py-5 px-4 border-right">
<div disabled class="col-md-6 grl-section">
<div class="col-lg-12 form-group">
#for (int i = 0; i < Model.GRLContactGroupList.Count(); i++)
{
#Html.CheckBoxFor(m => m.GRLContactGroupList[i].IsChecked) #(#Model.GRLContactGroupList[i].GroupName + " - " + #Model.GRLContactGroupList[i].ZONE) <br />
#for (int j = 0; j < Model.GRLContactGroupList[i].GRLContactList.Count(); j++)
{
#Html.CheckBoxFor(m => m.GRLContactGroupList[i].GRLContactList[j].IsChecked) #Model.GRLContactGroupList[i].GRLContactList[j].Name <br />
}
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-footer modal-footer py-4">
<div class="row">
<div class="col-lg-6 px-4">
<button id="submitBtn" type="submit" class="btn btn-primary">Save</button>
<button type="reset" class="btn btn-default color-theme">Clear</button>
</div>
</div>
</div>
</form>

FormCollection Empty in ASP.NET Mobile View

When I am using this code as web view, it works fine, but when with developer option in Chrome I select Mobile View, FormCollection shows empty strings in the controller
VIEW (Edit updtaed)
<div class="page product-details-page deal-product-details-page">
#using (Html.BeginForm("AddProductToCart_Details", "DealProduct", new { productId = Model.Id, shoppingCartTypeId = 1 }, FormMethod.Post))
{
<div class="page-body">
#using (Html.BeginRouteForm("Product", new { SeName = Model.SeName }, FormMethod.Post, new { id = "product-details-form" }))
{
#{
var dataDictAttributes = new ViewDataDictionary();
dataDictAttributes.TemplateInfo.HtmlFieldPrefix = string.Format("attributes_{0}", Model.Id);
#Html.Partial("~/Views/Product/_ProductAttributes.cshtml", Model.ProductAttributes, dataDictAttributes)
}
<!--gift card-->
#{
var dataDictGiftCard = new ViewDataDictionary();
dataDictGiftCard.TemplateInfo.HtmlFieldPrefix = string.Format("giftcard_{0}", Model.Id);
#Html.Partial("~/Views/Product/_GiftCardInfo.cshtml", Model.GiftCard, dataDictGiftCard)
}
<!--rental info-->
#{
var dataDictRental = new ViewDataDictionary();
dataDictRental.TemplateInfo.HtmlFieldPrefix = string.Format("rental_{0}", Model.Id);
#Html.Partial("~/Views/Product/_RentalInfo.cshtml", Model, dataDictRental)
}
<!--price & add to cart-->
#{
var dataDictPrice = new ViewDataDictionary();
dataDictPrice.TemplateInfo.HtmlFieldPrefix = string.Format("price_{0}", Model.Id);
#Html.Partial("~/Views/Product/_ProductPrice.cshtml", Model.ProductPrice, dataDictPrice)
#Html.Partial("~/Views/Product/_ProductTierPrices.cshtml", Model.TierPrices)
}
<!--wishlist, compare, email a friend-->
<!--attributes-->
#{
var item = #Model.AssociateProductAttributesList.Where(x => x.Item1 == data.Id).Select(x => x.Item2).ToList()[0];
bool isAttributes =false;
}
<div class="popup" data-popup="popup-#data.Id">
<div class="popup-inner">
<h2>#data.Name</h2>
<p>#data.ShortDescription</p>
<br />
#foreach (System.Collections.DictionaryEntry value in item)
{
var val = data.Id + "_" + value.Key.ToString();
isAttributes = true;
#*<div class="attributes">*#
<dl>
<dt id="product_attribute_label_19">
<label class="text-prompt">
#value.Key.ToString()
</label>
</dt>
<dd id="product_attribute_input_19" class="product_attribute_inputdiv_#val">
#Html.DropDownList("Attributes," + data.Id + "," + value.Key.ToString(), new SelectList((System.Collections.IEnumerable)value.Value, "Id", "Name"), "--- Please select ---")
</dd>
</dl>
#*</div>*#
}
<br />
<div onclick="ImageBlur('div_#data.Id')" class="buttons" style="text-align:left;">
<input class="button-1" data-popup-close="popup-#data.Id" type="button" value="Add to back" />
</div>
<a class="popup-close" data-popup-close="popup-#data.Id" href="#">x</a>
</div>
</div>
#if (item.Count == 0)
{
#Html.Hidden("Attributes," + data.Id + ",", "0")
<div class="popup" data-popup="popup-#data.Id">
<div class="popup-inner">
<h2>#data.Name</h2>
<p>#data.ShortDescription</p>
<div onclick="ImageBlur('div_#data.Id')" class="buttons" style="text-align:left;">
<input class="button-1" data-popup-close="popup-#data.Id" type="button" value="Add to back" />
</div>
<a class="popup-close" data-popup-close="popup-#data.Id" href="#">x</a>
</div>
</div>
}
#if (isAttributes)
{
<a style="color: blue;" data-popup-open="popup-#data.Id" href="#">
<img id="imgdiv_#data.Id" src="~/Themes/Playground/Content/img/dealselectattribut.png" class="select-atr-img" style="width: 50%; margin-bottom: 10px;"/>
</a>
}
</div>
}
</div>
<div>
</div>
#{
var dataDictAddToCart = new ViewDataDictionary();
dataDictAddToCart.TemplateInfo.HtmlFieldPrefix = string.Format("addtocart_{0}", Model.Id);
<div class="overview" style="width:100%; margin-left:auto">
#Html.Partial("~/Views/Product/_AddToCart.cshtml", Model.AddToCart, dataDictAddToCart)
</div>
}
</div>
}
</div>
}
</div>
Controller
public ActionResult AddProductToCart_Details(int productId, int shoppingCartTypeId, FormCollection form)
{
if (_productService.IsDealProducts(productId))
{
if (!IsCompleteSelected(form))
{
return Json(new
{
success = false,
message = " Plese select all associated product attribute "
});
}
}
//more code here
}
Normal View (Web View)
Mobile View
Form in form is not allowed. This is your issue.

getJSON data function doesnt work on IIS

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);
});

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