AngularJS + post the entire $scope for Controller in ASP.NET MVC - asp.net-mvc-3

guys.
I'm trying to call some AJAX Post trhu AngularJS, and I want to send all properties from my $scope variable. I have this form:
<div ng-controller="DiscountPrintsCtrl">
<div>
Choose the year:
<select ng-model="selectedYear" ng-change="searchCourses()">
<option ng-repeat="year in years" value="{{year.ID}}">{{year.Name}}</option>
</select>
</div>
<div>
Choose the course:
<select ng-model="selectedCourse" ng-change="searchStudents()">
<option ng-repeat="course in courses" value="{{course.ID}}">{{course.Nome}}</option>
</select>
</div>
<div>
Choose the student:
<select ng-model="selectedStudent" ng-change="searchStudentDetails()">
<option ng-repeat="student in students" value="{{student.ID}}">{{student.Name}}</option>
</select>
</div>
<div ng-model="studentDetails">
Details about the student:<br /><br />
<label>Name: {{studentDetails.Name}}</label><br />
<label>Number: {{studentDetails.Number}}</label><br />
<label>Print quote: {{studentDetails.PrintQuote}}</label><br />
</div>
<div>
<table>
<thead><tr>
<td></td>
<td>Title</td>
<td>Grade</td>
<td>Summary</td>
<td>Author</td>
<td>Number of pages</td>
</tr></thead>
<tbody>
<tr ng-repeat="publication in publications">
<td><input type="checkbox" ng-model="publication.Selected" /></td>
<td>{{publication.Title}}</td>
<td>{{publication.Grade}}</td>
<td>{{publication.Comments}}</td>
<td>{{publication.Author}}</td>
<td>{{publication.NumberOfPages}}</td>
</tr>
</tbody>
</table>
</div>
<button ng-click="submitForm()" value="Confirm discounts" />
And I have this JS:
<script type="text/javascript">
function DiscountPrintsCtrl($scope, $http) {
$http.get(url).success(function (years) {
$scope.years = years;
$scope.selectedYear = '';
});
$scope.searchCourses = function() {
var url = '/json/GetCoursesFromYear?' +
'selectedYear=' + $scope.selectedYear;
$http.get(url).success(function (courses) {
$scope.course = courses;
$scope.selectedCourse= '';
});
}
$scope.searchAlunosAnoSemestre = function() {
var url = '/json/GetStudentsFromCouse?' +
'selectedCourse=' + $scope.selectedCourse;
$http.get(url).success(function(students) {
$scope.students = students;
$scope.selectedStudent = '';
});
}
$scope.searchStudentDetails = function() {
var url = '';
url = '/json/GetStudentDetails?' +
'selectedStudent=' + $scope.selectedStudent;
$http.get(url).success(function(studentDetails) {
$scope.studentDetails= studentDetails;
});
url = '/json/GetPublicationsForStudent?' +
'selectedStudent=' + $scope.selectedStudent;
$http.get(url).success(function(publications) {
$scope.publications = publications;
});
}
$scope.submitForm = function () {
// How to submit the entire $scope???
}
}
Any idea? Any considerations about my JS code??
Thanks all!!!

You have typos to fix, friend:
In the .js:
$scope.course = courses;
Should be $scope.courses!
In the html:
{{course.Nome}}
Shouldn't it be:
{{course.Name}}
?
I see some Spanish (?) above there but everywhere else you say .Name so it's best to be consistent, right?
That said, it seems fine to load an object into your $scope from the external json data store as you seem do be doing in each function, loading from the json URLs. The commenters on your post didn't seem to recognize this? I think they believe you're trying to permanently store this data in $scope? Maybe I'm not seeing something that they are... but if you don't add your data model object sometime into $scope.something then {{something}} simply won't work, and neither will {{something.else}}.
Am I way off base here?

Related

How can I refresh my partial view on my parent index after a modal update to add new information?

I am certain this question has been asked before, I don't think there is anything unique about my situation but let me explain. I have my Index View (Parent), on that Index View there is a partial View Dataset Contacts "links" (child), I have an Add Contact button, which pops a Modal and allows me to submit the form data to add to the database, when I return I want to only refresh the partial view of links. Note: the Controller Action Dataset_Contacts below needs to fire in order to refresh the partial view (child). It might go without saying, but I don't see this happening with my current code. Any assistance will be appreciated.
on my Index View index.cshtml I have the following code to render my partial View
<div class="section_container2">
#{ Html.RenderAction("Dataset_Contacts", "Home"); }
</div>
Here is the controller:
[ChildActionOnly]
public ActionResult Dataset_Contacts()
{
// Retrieve contacts in the Dataset (Contact)
//Hosted web API REST Service base url
string Baseurl = "http://localhost:4251/";
var returned = new Dataset_Contact_View();
var dataset = new Dataset();
var contacts = new List<Contact>();
var contact_types = new List<Contact_Type>();
using (var client = new HttpClient())
{
dataset = JsonConvert.DeserializeObject<Dataset>(datasetResponse);
contact_types = JsonConvert.DeserializeObject<List<Contact_Type>>(ContactTypeResponse);
// Set up the UI
var ds_contact = new List<ContactView>();
foreach (Contact c in dataset.Contact)
{
foreach (Contact_Type t in contact_types)
{
if (c.Contact_Type_ID == t.Contact_Type_ID)
{
var cv = new ContactView();
cv.contact_id = c.Contact_ID;
cv.contact_type = t.Description;
returned.Dataset_Contacts.Add(cv);
}
}
}
}
return PartialView(returned);
}
Here is my Partial View Dataset_Contacts.cshtml
#model ResearchDataInventoryWeb.Models.Dataset_Contact_View
<table>
#{
var count = 1;
foreach (var ct in Model.Dataset_Contacts)
{
if (count == 1)
{
#Html.Raw("<tr>")
#Html.Raw("<td>")
<span class="link" style="margin-left:10px;">#ct.contact_type</span>
#Html.Raw("</td>")
count++;
}
else if (count == 2)
{
#Html.Raw("<td>")
<span class="link" style="margin-left:300px;">#ct.contact_type</span>
#Html.Raw("</td>")
#Html.Raw("</tr>")
count = 1;
}
}
}
</table>
Also on my Index.cshtml is my Add Contact button, which pops a modal
<div style="float:right;">
<span class="link" style="padding-right:5px;">Add</span>
</div>
jquery for the Modal:
var AddContact = function () {
var url = "../Home/AddContact"
$("#myModalBody").load(url, function () {
$("#myModal").modal("show");
})
};
Controller action for AddContact
public ActionResult AddContact()
{
return PartialView();
}
Modal for AddContact.cshtml
#model ResearchDataInventoryWeb.Models.Contact
<form id="contactForm1">
<div class="section_header2">Contact</div>
<div style="padding-top:5px;">
<table>
<tr>
<td>
<span class="display-label">UCID/Booth ID</span>
</td>
<td>
#Html.TextBoxFor(model => model.Booth_UCID, new { placeholder = "<Booth/UCID>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Type</span>
</td>
<td>
<select class="input-box" id="contact_type">
<option value="contact_type">Contact Type*</option>
<option value="dataset_admin">Dataset Admin</option>
<option value="dataset_Provider">Dataset Provider</option>
<option value="department">Department</option>
<option value="external_collaborator">External Collaborator</option>
<option value="principal_investigator">Principal Investigator</option>
<option value="research_center">Research Center</option>
<option value="vendor">Vendor</option>
</select>
</td>
</tr>
<tr>
<td>
<span class="display-label">Name</span>
</td>
<td>
#Html.TextBoxFor(model => model.First_Name, new { placeholder = "<First Name>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Last_Name, new { placeholder = "<Last Name>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Email</span>
</td>
<td>
#Html.TextBoxFor(model => model.Email, new { placeholder = "<Email 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Email_2, new { placeholder = "<Email 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Phone</span>
</td>
<td>
#Html.TextBoxFor(model => model.Phone_Number, new { placeholder = "<Phone 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Phone_Number_2, new { placeholder = "<Phone 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Job Title</span>
</td>
<td>
#Html.TextBoxFor(model => model.Title_Role, new { placeholder = "<Job Title>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Organization</span>
</td>
<td>
<input class="input-box" type="text" placeholder="<Organization>" />
</td>
</tr>
</table>
<div style="padding-left:10px; margin-top:10px;">
<textarea rows="3" placeholder="Notes"></textarea>
</div>
</div>
<div class="centerButton" style="margin-top: 30px;">
<div style="margin-left:30px">
<submit id="btnSubmit" class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">SAVE</span></submit>
</div>
<div style="margin-left:30px">
<submit class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">REMOVE</span></submit>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
var frm = $('#contactForm1').serialize()
$.ajax({
type: "POST",
url: "/Home/AddContact/",
data: frm,
success: function () {
$("#myModal").modal("hide");
}
})
})
})
</script>
and lastly Action for [HttpPost] AddContact(Contact data)
[HttpPost]
public ActionResult AddContact(Contact data)
{
// Update the Database here
return View();
}
My solution:
1. Change ActionResult to JsonResult
{
// Update the Database code
// END
return Json(new
{
dbUpdateResult = "success"
});
}
2. In Ajax:
//Ajax code
...
success: function (ajaxRespond) {
if(ajaxRespond.dbUpdateResult == "success"){
$("#myModal").modal("hide");
reloadTable()
}
}
Then you can use 1:
function reloadTable(){
$('#CONTAINER_ID').load('#Url.Action("Dataset_Contacts", "Home")');
}
Or 2:
function reloadTable(){
let myurl = '#Url.Action("Dataset_Contacts", "Home")';
$.ajax({
type: "GET",
url: myurl,
success: function (data, textStatus, jqXHR) {
$("#CONTAINER_ID").html(data);
},
error: function (requestObject, error, errorThrown) {
console.log(requestObject, error, errorThrown);
alert("Error: can not update table")
}
});
}
So you reload your partial view after successful dbupdate. Please tell me, if I'm wrong...

Get database record using AJAX, Knockout and JSON

I am fairly new to Knockout and Entity Framework and I have a problem where I cannot seem to output any JSON from an MVC 4 controller action via an AJAX call using Knockout onto an html page.
The table includes fields Email and RegsitrationNumber, these are used to validate the user.
If the user exists in the table then their country is displayed on the screen.
The profiler states a Status Code of 200 i.e OK. Can anyone help?
HTML ------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="./Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div>
<div>
<h2 id="title">Login</h2>
</div>
<div>
<label for="email">Email</label>
<input data-bind="value: $root.Email" type="text" title="Email" />
</div>
<div>
<label for="registrationnumber">Registration Number</label>
<input data-bind="value: $root.RegistrationNumber" type="text" title="RegistrationNumber" />
</div>
<div>
<button data-bind="click: $root.login">Login</button>
</div>
</div>
<table id="products1" data-bind="visible: User().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
<script src="./Scripts/knockout-2.2.0.js"></script>
<script src="./Scripts/knockout-2.2.0.debug.js"></script>
<script src="./Scripts/functions.js"></script>
</body>
</html>
JAVASCRIPT -----
function UserViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Name = ko.observable("Robbie");
self.Email = ko.observable("rob#test.com");
self.Occupation = ko.observable("Designer");
self.Country = ko.observable("UK");
self.RegistrationNumber = ko.observable("R009");
self.UserDate = ko.observable("06-04-2014");
var User = {
Name: self.Name,
Email: self.Email,
Occupation: self.Occupation,
Country: self.Country,
RegistrationNumber: self.RegistrationNumber,
UserDate: self.UserDate
};
self.User = ko.observable(); //user
self.Users = ko.observableArray(); // list of users
//Login
self.login = function ()
{
alert("login");
if (User.Email() != "" && User.RegistrationNumber() != "") {
$.ajax({
url: '/Admin/Login',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(User),
success: function (data) {
self.Users.push(data);
$('#title').html(data.Email);
}
}).fail(
function (xhr, textStatus, err) {
console.log('fail');
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
} else {
alert('Please enter an email and registration number');
}
};
}
var viewModel = new UserViewModel();
ko.applyBindings(viewModel);
ACTION -----
public ActionResult Login(string Email, string RegistrationNumber)
{
var user = from s in db.Users
select s;
user = user.Where(s => s.Email.ToUpper().Equals(Email.ToUpper())
&& s.RegistrationNumber.ToUpper().Equals(RegistrationNumber.ToUpper())
);
if (user == null)
{
return HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}
Looks like your binding is incorrect...
<table id="products1" data-bind="visible: Users().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
User().length should be Users().length.

Jquery Validation on Dom not displaying message

I stumbled upon some code that has jQuery validation which is triggered after an ajax call that adds items to the DOM. The validation is working but the message is missing. just the field is highlighted. I have been playing with this for a while to get it to work, but so far no luck. Any ideas, thoughts appreciated.
$('#add-other-income-link').click(function (event) {
event.preventDefault();
var otherIncomesCount = $('#numberOfNewOtherIncomes').val();
$('div[hideCorner = yep]').show();
var url = $(this).attr('href');
if (url) {
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function (data) {
$('#additional-other-income').append(data);
var count = otherIncomesCount;
var id = 0;
$('#additional-other-income').find('table.other-income-table').each(function (i, item) {
id = $(item).find('input.other-income-id');
var additionalIncomeTypeIdLabel = $(item).find('label.other-income-type-id-label');
var amountLabel = $(item).find('label.other-income-amount-label');
var additionalIncomeTypeIdMenu = $(item).find('select.other-income-type-id');
var amountTextBox = $(item).find('input.other-income-amount');
var idIndexer = 'OtherIncome_' + count + '__';
var nameIndexer = 'OtherIncome[' + count + '].';
var indexer = '[' + i + ']';
id.attr('id', idIndexer + 'Id').attr('name', nameIndexer + 'Id');
additionalIncomeTypeIdLabel.attr('for', idIndexer + 'AdditionalIncomeTypeId');
amountLabel.attr('for', idIndexer + 'Amount');
additionalIncomeTypeIdMenu.attr('id', idIndexer + 'AdditionalIncomeTypeId').attr('name', nameIndexer + 'AdditionalIncomeTypeId');
amountTextBox.attr('id', idIndexer + 'Amount').attr('name', nameIndexer + 'Amount').attr('data-val', 'true');
++count;
addOtherIncomeValidation(item);
});
The validation succeeds for both required on additionalIncomeTypeIDMenu, and required and positive on amountTextBox, but the messages for both fail to show up:
function addOtherIncomeValidation(container) {
if (container) {
var additionalIncomeTypeIdMenu = $(container).find('select.other-income-type-id');
var amountTextBox = $(container).find('input.other-income-amount');
$(additionalIncomeTypeIdMenu).rules('add', {
required: true,
messages: {
required: 'Please select an income type'
}
});
$(amountTextBox).rules('add', {
required: true,
positive: true,
messages: { positive: 'must be positive number'
}
});
}
}
BTW The ajax call returns a partial EditorTemplate here, which you can see uses ValidationMessageFor.
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
#Html.HiddenFor(x => x.Id, new { #class = "other-income-id" })
#Html.LabelFor(x => x.AdditionalIncomeTypeId, "Type:", new { #class = "other-income-type-id-label" })
<br />#Html.ValidationMessageFor(x => x.AdditionalIncomeTypeId)
</td>
<td>
#Html.LabelFor(x => x.Amount, "Amount:", new { #class = "other-income-amount-label" })
<br />#Html.ValidationMessageFor(x => x.Amount)
</td>
<td> </td>
</tr>
<tr>
<td>#Html.DropDownListFor(x => x.AdditionalIncomeTypeId, new SelectList(Model.AdditionalIncomeTypes, "Value", "Text", Model.AdditionalIncomeTypeId), "--- Select One ---", new { #class = "other-income-type-id" })</td>
<td>
#Html.EditorFor(x => x.Amount, "Money", new { AdditionalClasses = "other-income-amount" })
</td>
<td>
#{
int? otherIncomeId = null;
var removeOtherIncomeLinkClasses = "remove-other-income-link";
if (Model.Id == 0)
{
removeOtherIncomeLinkClasses += " new-other-income";
}
else
{
otherIncomeId = Model.Id;
}
}
#Html.ActionLink("Remove", "RemoveOtherIncome", "Applicant", new { applicationId = Model.ApplicationId, otherIncomeId = otherIncomeId }, new { #class = removeOtherIncomeLinkClasses })<img class="hide spinner" src="#Url.Content("~/Content/Images/ajax-loader_16x16.gif")" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
HTML:
<div id="OtherIncome" class="applicant-section">
<h2 class="header2">Other Income</h2>
<div class="cornerForm">
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
<input class="other-income-id" data-val="true" data-val-number="The field Id must be a number." id="OtherIncome_0__Id" name="OtherIncome[0].Id" type="hidden" value="385" />
<label class="other-income-type-id-label" for="OtherIncome_0__AdditionalIncomeTypeId">Type:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[0].AdditionalIncomeTypeId" data-valmsg-replace="true"></span>
</td>
<td>
<label class="other-income-amount-label" for="OtherIncome_0__Amount">Amount:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[0].Amount" data-valmsg-replace="true"></span>
</td>
<td> </td>
</tr>
<tr>
<td><select class="other-income-type-id" data-val="true" data-val-number="The field AdditionalIncomeTypeId must be a number." id="OtherIncome_0__AdditionalIncomeTypeId" name="OtherIncome[0].AdditionalIncomeTypeId"><option value="">--- Select One ---</option>
<option value="1">Alimony</option>
<option value="2">Child Support</option>
<option value="3">Disability</option>
<option value="4">Investments</option>
<option selected="selected" value="5">Rental Income</option>
<option value="6">Retirement</option>
<option value="7">Secondary Employment</option>
<option value="8">Separate Maintenance</option>
</select></td>
<td>
<input class="money other-income-amount" data-val="true" data-val-number="The field Amount must be a number." id="OtherIncome_0__Amount" name="OtherIncome[0].Amount" style="" type="text" value="0.00" />
</td>
<td>
<a class="remove-other-income-link" href="/Applicant/RemoveOtherIncome/XNxxxxx753/385">Remove</a><img class="hide spinner" src="/Content/Images/ajax-loader_16x16.gif" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
</div>
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
<input class="other-income-id" data-val="true" data-val-number="The field Id must be a number." id="OtherIncome_1__Id" name="OtherIncome[1].Id" type="hidden" value="412" />
<label class="other-income-type-id-label" for="OtherIncome_1__AdditionalIncomeTypeId">Type:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[1].AdditionalIncomeTypeId" data-valmsg-replace="true"></span>
</td>
<td>
<label class="other-income-amount-label" for="OtherIncome_1__Amount">Amount:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[1].Amount" data-valmsg-replace="true"></span>
</td>
<td> </td>
</tr>
<tr>
<td><select class="other-income-type-id" data-val="true" data-val-number="The field AdditionalIncomeTypeId must be a number." id="OtherIncome_1__AdditionalIncomeTypeId" name="OtherIncome[1].AdditionalIncomeTypeId"><option value="">--- Select One ---</option>
<option selected="selected" value="1">Alimony</option>
<option value="2">Child Support</option>
<option value="3">Disability</option>
<option value="4">Investments</option>
<option value="5">Rental Income</option>
<option value="6">Retirement</option>
<option value="7">Secondary Employment</option>
<option value="8">Separate Maintenance</option>
</select></td>
<td>
<input class="money other-income-amount" data-val="true" data-val-number="The field Amount must be a number." id="OtherIncome_1__Amount" name="OtherIncome[1].Amount" style="" type="text" value="22.00" />
</td>
<td>
<a class="remove-other-income-link" href="/Applicant/RemoveOtherIncome/XN42093753/412">Remove</a><img class="hide spinner" src="/Content/Images/ajax-loader_16x16.gif" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
</div>
<div id="additional-other-income"></div>
<input id="numberOfNewOtherIncomes" name="numberOfNewOtherIncomes" type="hidden" value="0" />
<input data-val="true" data-val-number="The field OriginalOtherIncomeTotal must be a number." id="OriginalOtherIncomeTotal" name="OriginalOtherIncomeTotal" type="hidden" value="22.0000" />
<a class="editable-link" href="/Applicant/AddOtherIncome?appId=XNxxxxx753" id="add-other-income-link">Add Other Income</a>
</div> </div>
Validation code:
$.validator.addMethod('positive', function(value, element) {
var check = true;
if (value < 0) {
check = false;
}
return this.optional(element) || check;
}, "Value must be a positive number."
);
I didn't think I would find my own answer but I did. first I have to apologize for my response to #Sparky with his request for rendered HTML. I did a "View page source" but that didn't include all the stuff which was added from the ajax call after the server delivered it's stuff. I suspect if I did include the extra DOM stuff at first, you would have pinpointed the issue sooner. My bad. Now on to the answer.
It appears that when injecting an EditorTemplate into the DOM in the way shown above, it doesn't properly process the page like you would expect in MVC. The code for #Html.ValidationMessageFor simply does not get parsed AT ALL. I am a little new to validation as you can see so I don't know why it behaves this way. To solve my problem here is what I did:
I updated my Editor Template slightly to look like this:
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
#Html.HiddenFor(x => x.Id, new { #class = "other-income-id" })
#Html.LabelFor(x => x.AdditionalIncomeTypeId, "Type:", new { #class = "other-income-type-id-label" })
<br />
#Html.ValidationMessageFor(x=>x.AdditionalIncomeTypeId)
<span id="AdditionalIncomeTypeIdValidation"></span>
</td>
<td>
#Html.LabelFor(x => x.Amount, "Amount:", new { #class = "other-income-amount-label" })
<br />
#Html.ValidationMessageFor(x=>x.Amount)
<span id="amountValidation"></span>
</td>
<td> </td>
</tr>
<tr>
<td>#Html.DropDownListFor(x => x.AdditionalIncomeTypeId, new SelectList(Model.AdditionalIncomeTypes, "Value", "Text", Model.AdditionalIncomeTypeId), "--- Select One ---", new { #class = "other-income-type-id" })</td>
<td>
#Html.EditorFor(x => x.Amount, "Money", new { AdditionalClasses = "other-income-amount" })
</td>
<td>
#{
int? otherIncomeId = null;
var removeOtherIncomeLinkClasses = "remove-other-income-link";
if (Model.Id == 0)
{
removeOtherIncomeLinkClasses += " new-other-income";
}
else
{
otherIncomeId = Model.Id;
}
}
#Html.ActionLink("Remove", "RemoveOtherIncome", "Applicant", new { applicationId = Model.ApplicationId, otherIncomeId = otherIncomeId }, new { #class = removeOtherIncomeLinkClasses })<img class="hide spinner" src="#Url.Content("~/Content/Images/ajax-loader_16x16.gif")" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
Notice the new span tags, which is are added next to the #Html.ValidationMessageFor.
then in my success function from the ajax call in javascript I made these changes:
$('#add-other-income-link').click(function (event) {
event.preventDefault();
var count = $('#numberOfNewOtherIncomes').val();
$('div[hideCorner = yep]').show();
var url = $(this).attr('href');
if (url) {
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function (data) {
$('#additional-other-income').append(data);
var id = 0;
$('#additional-other-income').find('table.other-income-table').each(function (i, item) {
id = $(item).find('input.other-income-id');
var additionalIncomeTypeIdLabel = $(item).find('label.other-income-type-id-label');
var amountLabel = $(item).find('label.other-income-amount-label');
var additionalIncomeTypeIdMenu = $(item).find('select.other-income-type-id');
var amountTextBox = $(item).find('input.other-income-amount');
var amountValidation = $(item).find('#amountValidation');
var typeIdValidation = $(item).find('#AdditionalIncomeTypeIdValidation');
var idIndexer = 'OtherIncome_' + count + '__';
var nameIndexer = 'OtherIncome[' + count + '].';
var indexer = '[' + i + ']';
amountValidation.attr('class', 'field-validation-valid')
.attr('data-valmsg-for', nameIndexer + 'Amount')
.attr('data-valmsg-replace','true');
typeIdValidation.attr('class', 'field-validation-valid')
.attr('data-valmsg-for', nameIndexer + 'AdditionalIncomeTypeId')
.attr('data-valmsg-replace','true');
id.attr('id', idIndexer + 'Id').attr('name', nameIndexer + 'Id');
additionalIncomeTypeIdLabel.attr('for', idIndexer + 'AdditionalIncomeTypeId');
amountLabel.attr('for', idIndexer + 'Amount');
additionalIncomeTypeIdMenu.attr('id', idIndexer + 'AdditionalIncomeTypeId').attr('name', nameIndexer + 'AdditionalIncomeTypeId');
amountTextBox.attr('id', idIndexer + 'Amount').attr('name', nameIndexer + 'Amount').attr('data-val', 'true');
++count;
addOtherIncomeValidation(item);
notice I am manually adding in the missing validation spans that were not rendering. Now the validation message shows up at validation! Yay. I am not sure however that this is the best fix. It looks and smells like a hack, but I got it to work. I am sure it can be done a better way. Thanks again for interaction and feedback.

codeigniter - display database query result on same form using input data

I have trawled the net for sometime now trying to find a solution which cold assist me, but have had no luck.
I have a simple sales form in which the user selects a product from a drop down list. on selecting a value, I want the input box value to get passed to a database query, and the query result (price) be displayed on the form. if possible I want the result to populate an input box so the salesman can adjust as needed.
I am using codeigniter which makes finding a good example quite difficult.
Controller
function new_blank_order_lines()
{
$this->load->view('sales/new_blank_order_lines');
}
Model
function get_sku_price($q){
$this->db->select('ProductPrice');
$this->db->where('ProductCode', $q);
$query = $this->db->get('ProductList');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['ProductPrice'])); //build an array
}
$this->output->set_content_type('application/json')->set_output(json_encode($row_set));
}
}
View
<table>
<tr><td>Product</td><td>Price</td></tr>
<tr>
<td><select name="product">
<option="sku1">product 1</option>
<option="sku2">product 2</option>
<option="sku3">product 3</option>
<select></td>
<td><input type="text" id="price" name="price" /></td>
</tr>
</table>
I have loaded the jquery library, 1.9.1.
I have got autocomplete working but the sytax is just not the same.
So what I am wanting, is that when I select a product code from the product drop down list, the value is passed to the model, the query result(price) is then displayed in the input box price.
Can anyone provide some insight on how to do this, or a good working example?
Thanks a million, this community is awesome!
Fabio
Controller:
function new_blank_order_lines()
{
$this->load->view('sales/new_order');
}
The view:
<script>
$("#product").change(function () {
//get the value of the select when it changes
var value = $("#product").val()
//make an ajax request posting it to your controller
$.post('<?=base_url("sales/get_sku_prices")?>', {data:value},function(result) {
//change the input price with the returned value
$('#price').value(result);
});
});
</script>
<table>
<tr><td>Product</td><td>Price</td></tr>
<tr>
<td><select name="product" id="product">
<option value="sku1">product 1</option>
<option value="sku2">product 2</option>
<option value="sku3">product 3</option>
</select></td>
<td><input type="text" id="price" name="price" /></td>
</tr>
</table>
Controller to fetch database data:
function get_sku_prices(){
//check if is an ajax request
if($this->input->is_ajax_request()){
//checks if the variable data exists on the posted data
if($this->input->post('data')){
$this->load->model('Sales_model');
//query in your model you should verify if the data passed is legit before querying
$price = $this->your_model->get_sku_price($this->input->post('data', TRUE));
echo $price;
}
}
}
Model:
function get_sku_price($q){
$this->db->select('ProductPrice');
$this->db->where('ProductCode', $q);
$query = $this->db->get('ProductList');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['ProductPrice'])); //build an array
}
$this->output->set_content_type('application/json')->set_output(json_encode($row_set));
}
}
Your View:
<table>
<tr>
<td>Product</td>
<td>Price</td>
</tr>
<tr>
<td>
<select name="product" id="product">
<option value="sku1">product 1</option>
<option value="sku2">product 2</option>
<option value="sku3">product 3</option>
</select>
</td>
<td>
<input type="text" id="price" name="price" />
</td>
</tr>
</table>
The javascript
<script>
$("#product").change(function () {
//get the value of the select when it changes
var value = $("#product").val()
//make an ajax request posting it to your controller
$.post('<?=site_url("controller/function")?>', {data:value},function(result) {
//change the input price with the returned value
$('#price').value(result);
});
});
</script>
The controller:
public function your_funtion(){
//check if is an ajax request
if($this->input->is_ajax_request()){
//checks if the variable data exists on the posted data
if($this->input->post('data')){
$this->load_model('your_model')
//query in your model you should verify if the data passed is legit before querying
$price = $this->your_model->get_price($this->input->post('data', TRUE));
echo $price;
}
}
}
use jquery's ajax,post or get and change event..using post here
example..
$('select[name="product"]').change(function(){
var val=$(this).val();
$.post('path/to/controller',{data:val},function(result){
$('#price').val(result.price);
}, "json");
});
conroller funciton
$product=$this->input->post('data'); //this will give you the selected value of select
//make query to db in model..get price and
$price = ..//price that you got from db
echo json_encode(array('price'=> $price));

Data does not display after navigate page

i'm having problem. i have a survey form, in this form i used also the ajax to call some of the data. when user click cancel, i want it to navigate to other page where it display the list of data in listview using ajax. for the clicking and navigation part, i've succeed to bring it to the page that i want, but the problem is, it does not display anymore the list of data. I used the same way as i did for other page but for this i can't get..any help? i've gone through my code several times but i can't get what makes it wrong. this is my code for the page survey form:
$('#MrateCourse').live('pageinit', function(){
var rowInput = "1";
var pageInput = "1";
var idInput = "${courseId}";
var regNoInput = "${regNo}";
$.ajax({
url: '${pageContext.request.contextPath}/getRegisteredClassesDetails.html',
data: ( {rows: rowInput, page: pageInput, courseId: idInput, regNo: regNoInput}),
type: 'POST',
success: function(json_results){
$('#list').append('<ul></ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(courseId) {
html = ' Course Name :
+ '<b>' + json_results.rows[courseId].courseName + '</b>';
html += '</br> Registered Person :
+ '<b>' + json_results.rows[courseId].fullName + '</b>';
listItems.append(html);
});
$('#list ul').listview();
}
});
});
$(function() {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
if(day<10){
day='0'+day;
}
if(month<10){
month='0'+month;
}
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes;
$('#dateTime').html("<b>" + month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + suffix + "</b>");
});
<form id="" action="${pageContext.request.contextPath}/MRegisteredClasses.phone" method="POST">
<table>
<tr>
<td>Date:
<span id="dateTime"></span><br/></td>
</tr>
<tr>
<td>Company:</td>
<td><input type="text" value=""/><br/></td>
</tr>
<tr>
<td><b>Based on your experience in this course, please answer<br>the following questions:
<br>1 = Strongly Disagree, 5 = Strongly Agree</b></td>
</tr>
<tr>
<td>The web-based training media used was of high quality.</td>
<td><select>
<option value=""></option>
<option value="5">5</option>
<option value="5">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br/></td>
</tr>
<tr>
<td>I had enough time to learn the subject matter covered in the course.</td>
<td><select>
<option value=""></option>
<option value="5">5</option>
<option value="5">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br/></td>
</tr>
<tr>
<td>My knowledge and/or skills increased as a result of this course.</td>
<td><select>
<option value=""></option>
<option value="5">5</option>
<option value="5">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br/></td>
</tr>
<tr>
<td>Additional comments or ideas to improve this course:</td>
</tr>
<tr>
<td><textarea rows="3" ></textarea></td>
</tr>
<tr>
<td>What additional topics would you like to see addressed in a future online course?</td>
</tr>
<tr>
<td><textarea rows="3"></textarea></td>
</tr>
<tr>
<td align="left">
<input type="submit" data-inline="true" id="submit" value="Submit This Survey" class="ui-btn-right"
onClick="confirm( 'Thanks for filling the survey' )"/>
<a href="${pageContext.request.contextPath}/MRegisteredClasses.phone" class="ui-btn-right"
data-role="button" data-inline="true">Cancel</a>
</td>
</tr>
</table>
</form>
and this is my code for the page that it need to navigate.
<div data-role="page" id="MregisteredClasses">
<div data-role="content">
<h3>Courses Name</h3>
<p id="note">*Click at the courses to view the details</p>
<h1></h1>
<div id="courseName">
<ul data-role="listview" data-inset="true" id="list"></ul>
<script type="text/javascript">
$('#MregisteredClasses').on('pageinit', function(){
var rowInput = "1";
var pageInput = "1";
$.ajax({
url: '${pageContext.request.contextPath}/getRegisteredClassesData.html',
data: ( {rows : rowInput , page : pageInput}),
type: 'POST',
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true" data-split-icon="gear"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(key) {
html = '<li <h3><a href="${pageContext.request.contextPath}/MRegisteredClassesDetail.phone?courseId='
+ [json_results.rows[key].courseId] + '&regNo=' + [json_results.rows[key].regNo] +
'"rel="external">' + json_results.rows[key].courseName+ '</a></h3>'
+ '<a href="${pageContext.request.contextPath}/MRateCourse.phone?courseId='
+ [json_results.rows[key].courseId] + '&regNo=' + [json_results.rows[key].regNo] +
'"rel="external">RATE THIS COURSE</a>';
listItems.append(html);
});
$('#list ul').listview();
},
});
});
</script>
</div>
</div><!-- /content -->
I got it already.. I add data-ajax="false" to my form.

Resources