How to call user control method using jQuery AJAX in Asp.Net - c#

Here is the acsx page.
I have two drop down in Bootstrap modal (State and City).
Based on the state selection, City dropdown should populate option.
I have created two methods in code behind for state FillStatedata() and for city getCitydata().
I need to call getCitydata() method on state selection change using jQuery AJAX and then bind the city data with city drop down.
I am getting Statename on state change but not able to executive getCitydata() method using statename as parameter.
Why?
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Registeration.ascx.cs" Inherits="WebApplication1.UserControl.Registeration" %>
<%# Import Namespace = "System.Web.Security" %>
<script src="~/scripts/jquery-1.10.2.js"></script>
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<!--jquery start here-->
<script>
$(document).ready(function () {
var getSelState;
$("#State").change(function () {
$.ajax({
type: "POST", //HTTP method
url: "UserControl/Registeration.ascx/getCitydata", //page/method name
data: alert("{'Statename':'" + $('#State').val() + "'}"), //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) { //handle the callback to handle response
//request was successful. so Retrieve the values in the response.
}
})
});
});
</script>
<input type="hidden" id="myhiddenField" name="myhiddenField" value="" ClientIDMode="Static" runat="server" />
<div class="form-horizontal" role="form" runat="server">
New User?
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Register</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="full-name" class="col-sm-2 control-label">FullName:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="full-name">
</div>
</div>
<div class="form-group">
<label for="User-Name" class="col-sm-2 control-label">Username:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="User-Name">
</div>
</div>
<div class="form-group">
<label for="Create-Password" class="col-sm-2 control-label">Create Password:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Create-Password">
</div>
</div>
<div class="form-group">
<label for="confirm-Password" class="col-sm-2 control-label">Confirm Password:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Confirm-Password">
</div>
</div>
<div class="form-group">
<label for="Mobile-Number" class="col-sm-2 control-label">Mobile No:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Mobile-Number">
</div>
</div>
<div class="form-group">
<label for="State" class="col-sm-2 control-label">State:</label>
<div class="col-sm-10">
<select class="form-control" id="State" runat="server" ClientIDMode="Static">
</select>
</div>
</div>
<div class="form-group">
<label for="City" class="col-sm-2 control-label">City:</label>
<div class="col-lg-10">
<select class="form-control" id="City" runat="server" DataTextField="Cityname"
DataValueField="Cityname"></select>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="button" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-primary">Cancel</button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>

First things first.
just use one library either min for prod or non min for dev.
data:{} should have to be an object or string value.
use one of it:
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
var getSelState;
$("#State").change(function() {
$.ajax({
type: "POST", //HTTP method
url: "UserControl/Registeration.ascx/getCitydata", //page/method name
data: "{'Statename':'" + this.value + "'}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) { //handle the callback to handle response
console.log(msg);
}
});
});
});
</script>

function getCitydata()(obj) {
var ddlcity = document.getElementById('<%= ddlcity.ClientID %>');
ddlcity.innerHTML = '';
$.support.cors = true;
var serviceUrl = '/ashx/map/Address.ashx';
if (serviceUrl.indexOf('?') > -1)
serviceUrl += '&jsonp='
else
serviceUrl += '?jsonp='
serviceUrl += '?&type=1&StateId=';
serviceUrl += document.getElementById('<%= ddlState.ClientID%>').value;
$.ajax({
type: 'GET',
crossDomain: true,
async: false,
contentType: 'application/json; charset = utf-8',
url: serviceUrl,
data: '{}',
dataType: 'jsonp',
success: function (data) {
if (data != null && data.length > 0) {
$.map(data, function (item, index) {
var newListItem = document.createElement('option');
newListItem.text = item.City;
newListItem.value = item.CityId;
ddlcity.options.add(newListItem);
});
}
},
error: function (error) {
alert('error ' + error);
}
});
} // getCitydata()
To use this function you have to create one ashx file eg. Address.ashx file which consist method for getting the data from database

Related

How to trigger Model Validation inside modal? .NET 5

i Have problem when i try the model validation by trying to fill the form by false.
And when i try to submit with the wrong value (not valid by model validator) it redirects to the page (without model).
Here's the screenshot :
Customer Index
redirect to Customer Create Page when i submit
Here's the code
CONTROLLER
//POST CREATE
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(Models.Customer obj)
{
if (ModelState.IsValid)
{
_db.Customers.Add(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
//GET DELETE
public IActionResult Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var obj = _db.Customers.Find(id);
if (obj == null)
{
return NotFound();
}
return PartialView(obj);
}
Model
public class Customer
{
[Key]
public int Id { get; set; }
[DisplayName("Nama Customer")]
[Required]
[MaxLength(81, ErrorMessage ="Tidak boleh melebihi 81 Karakter")]
public string Nama { get; set; }
public string Alamat { get; set; }
[Phone]
[Required]
public string Telp { get; set; }
}
Index.HTML Button Create
<button id="btnAddCustomer" class="btn btn-primary">Tambah Customer</button>
JS
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddCustomer").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Create", "Customer")',
contentType: "application/json; charset=utf-8",
data: null,
datatype: "json",
success: function (data) {
$('#modalBody').html(data);
$('#modalCustomer').modal(options);
$('#modalCustomer').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
});
CREATE CSHTML
<form method="post" asp-action="Create">
<div class="border p-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row">
<div class="col-4">
</div>
<div class="col-4">
<h2 class="text-black-50 pl-3">Add Customer</h2>
</div>
<div class="col-4">
</div>
</div>
<div class="row">
<div class="col-12 form-horizontal">
<div class="form-group row">
<div class="col-12 form-group">
<label asp-for="Nama"></label>
<input asp-for="Nama" class="form-control" />
<span asp-validation-for="Nama" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Telp"></label>
<input asp-for="Telp" class="form-control" />
<span asp-validation-for="Telp" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Alamat"></label>
<input type="text" asp-for="Alamat" class="form-control" />
#*validasi form*#
<span asp-validation-for="Alamat" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-6">
</div>
<div class="col-6">
</div>
<div class="col-6">
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
<input type="submit" class="btn btn-info w-75" value="create" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-danger w-75">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
Thank you (:
And when i try to submit with the wrong value (not valid by model
validator) it redirects to the page (without model).
You use return View(obj); when modelstate is not valid. So it will return view with model and the view name should be the action name(Create) if you do not specific view name. So this result is correct by using your code.
Here is a working demo:
Index.cshtml:
<button id="btnAddCustomer" class="btn btn-primary"> Tambah Customer</button>
<div class="modal fade" id="modalCustomer" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalBody">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#section Scripts{
<script>
$(document).ready(function () {
$("#btnAddCustomer").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Create", "Customer")',
contentType: "application/json; charset=utf-8",
data: null,
datatype: "json",
success: function (data) {
$('#modalBody').html(data);
//$('#modalCustomer').modal(options);
$('#modalCustomer').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
});
</script>
}
Create.cshtml:
#model Customer
#{
Layout = null; //be sure add this...
}
<form method="post" asp-action="Create">
<div class="border p-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row"><div class="col-4"></div><div class="col-4"><h2 class="text-black-50 pl-3">Add Customer</h2></div><div class="col-4"></div></div>
<div class="row">
<div class="col-12 form-horizontal">
<div class="form-group row">
<div class="col-12 form-group">
<label asp-for="Nama"></label>
<input asp-for="Nama" class="form-control" />
<span asp-validation-for="Nama" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Telp"></label>
<input asp-for="Telp" class="form-control" />
<span asp-validation-for="Telp" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Alamat"></label>
<input type="text" asp-for="Alamat" class="form-control" />
<span asp-validation-for="Alamat" class="text-danger"></span>
</div>
</div>
<div class="form-group row"><div class="col-6"></div><div class="col-6"></div><div class="col-6"></div></div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
#*change here..........*#
<input type="button" id="btn" class="btn btn-info w-75" value="create" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-danger w-75">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
JS in Create.cshtml:
<script>
$(document).on('click', '#modalCustomer #btn', function () {
var options = {};
options.type = "POST";
options.url = "/Customer/create";
options.dataType = "JSON";
options.cache = false;
options.async = true;
options.data = $("form").serialize();
options.success = function (data) {
//do your stuff...
$('#modalCustomer').modal('hide');
//if you don't want to stay in Index
//add the following code..
// window.location.href = "/home/privacy";
};
options.error = function (res) {
$('#modalBody').html(res.responseText);
};
$.ajax(options);
});
</script>
Update:
If modelstate is invalid, it will get into options.error and display the error message in modal. If modelstate is valid, it will get into options.success, you could redirect by using window.location.href or hide the modal by $('#modalCustomer').modal('hide');, just do your stuff.
Backend code should be like below:
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(Customers obj)
{
if (ModelState.IsValid)
{
_db.Customers.Add(obj);
_db.SaveChanges();
return Json(new { success = true }); //change this...
}
return View(obj);
}

Viewbag value not show in ASP.NET MVC view

I am using C# and ASP.NET MVC and try to pass data from the controller to the view. When I debug data show in viewbag but not show in view. The error is undefined. I don't know why this code shows an error.
This is the screenshot:
Screenshot of Debug Result
C# code:
public JsonResult mselectCOACodes(string gl_code)
{
ViewBag.mainCode = gl_code.Substring(0, 2) + "-00-00-0000";
if (ViewBag.mainCode != "")
{
ViewBag.mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
}
return Json("", JsonRequestBehavior.AllowGet);
}
jQuery:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#txtvglcode").change(function () {
$.ajax({
type: "GET",
url: "/ChartofAccount/mselectCOACodes",
data: {
gl_code: $("#txtvglcode").val()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
View
<div class="col-sm-6">
<div class="col-sm-3">
<div class="form-group">
<b>Main Code</b>
<div class="form-line">
<input type="text" id="txtglmainCode"
value="#ViewBag.mainCode" class="form-control" placeholder="" />
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<b>Description</b>
<div class="form-line">
<input type="text" id="txtmainDescription"
value="#ViewBag.mainDesc" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
Firstly, don't use #ViewBag to store the input value, because you cannot access its value inside your C# code.
Here is C# code:
public JsonResult mselectCOACodes(string gl_code)
{
string mainCode = gl_code.Substring(0, 2) + "-00-00-0000";
if (mainCode != "")
{
string mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
}
return Json(mainDesc, JsonRequestBehavior.AllowGet);
}
Here is JQuery:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#txtvglcode").change(function () {
$.ajax({
type: "GET",
url: "/ChartofAccount/mselectCOACodes",
data: {
gl_code: $("#txtvglcode").val()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (mainDesc) {
$("#txtmainDescription").val(mainDesc);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
View:
<div class="col-sm-6">
<div class="col-sm-3">
<div class="form-group">
<b>Main Code</b>
<div class="form-line">
<input type="text" id="txtglmainCode"
value="" class="form-control" placeholder="" />
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<b>Description</b>
<div class="form-line">
<input type="text" id="txtmainDescription"
value="" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>

asp.net mvc controller return json List<T> unknown error

I'm simply trying to send back the List collection from the controller to the ajax function as JSON string, and for it to be recieved so i can manipulate the view.
I've done this before with collections but i can't see what the issue is, i get the required json as per the image link at the bottom. However i see no error apart from "json response - undefined" in the other link for the browser console when debugging.
I've already tried:
1. creating a new SalaryCalculator object of data (which posts back okay)
2. also created an anonymous type (which again posts back fine)
Controller method
[HttpPost]
public ActionResult GetSalaryCalculation(List<SalaryCalculator> form)
{
foreach (var entry in form)
{
entry.Tax = TaxCalculation(entry.Salary);
entry.MonthlyNet = MonthlyCalculation(entry.Salary, entry.Tax);
entry.WeeklyNet = WeeklyCalculation(entry.MonthlyNet);
entry.HourlyRate = HourlyCalculation(entry.WeeklyNet, entry.WeeklyHours);
if (entry.OverTimeHours > 0)
{
entry.OvertimeTotal = OvertimeCalculation(entry.OverTimeHours, entry.HourlyRate);
}
entry.OvertimeSalaryTotal = TotalCombinedCalculation(entry.MonthlyNet, entry.OvertimeTotal);
entry.TaxCode = "tax";
if (entry.Pension > 0)
{
entry.Pension = PensionCalculation(entry.OvertimeSalaryTotal, entry.Pension);
}
if (entry.StudentLoan > 0)
{
entry.StudentLoan = StudentLoanCalculation(entry.OvertimeSalaryTotal, entry.StudentLoan);
}
}
return Json(form, JsonRequestBehavior.AllowGet);
//return Content(JsonConvert.SerializeObject(form));
}
AJAX call
initialise: function () {
$("#calculateAmount").on("click", function () {
var formData = [
{
Salary: $("#salaryAmount").val(),
WeeklyHours: $("#hoursWorked").val(),
StudentLoan: $("#studentValidation").val(),
Pension: $("#pensionValidation").val(),
OverTimeHours: $("#overtimeValidation").val()
}
];
//console.log(formDataArray);
Ajax.fn.ajaxPost("GetSalaryCalculation",
function (jsonSuccess) {
console.log(jsonSuccess);
},
function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
},
{ form: formData }
);
});
}
Processing AJAX
$.ajax({
type: "POST",
url: "/Home/" + sFunction,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: data === null ? null : JSON.stringify(data),
success: function (response, status, jqXhr) {
if (typeof response.d !== "undefined") {
onSuccess(response.d, status, jqXhr, passThroughData);
} else {
onSuccess(response, status, jqXhr, passThroughData);
}
},
error: function (jqXhr, status, errorName) {
// Handle generic errors if they exist, otherwise forward to error handler
if (jqXhr.status === 401) {
// Unauthorised. Force a refresh
window.location.href = window.location.href;
return;
}
else if (status === "timeout") {
// Function call timeout
}
onError(jqXhr, status, errorName, passThroughData);
},
timeout: iTimeoutMillis,
});
Index View
<form id="calculateForm">
<div class="form-group row">
<div class="col-sm-10">
<input type="text" class="form-control" id="salaryAmount" placeholder="Salary amount £" aria-label="Salary Amount" aria-describedby="salary Amount" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="text" class="form-control" id="hoursWorked" placeholder="Weekly hours worked" aria-label="Hours Worked" aria-describedby="Hours Worked" required>
</div>
</div>
<div class="form-group row collapse" id="studentLoan">
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Student loan £" aria-label="Student Loan" id="studentValidation" aria-describedby="Student Loan">
</div>
</div>
<div class="form-group row collapse" id="pensionPayment">
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Pension Payment £" aria-label="Pension Payment" id="pensionValidation" aria-describedby="Pension Payment">
</div>
</div>
<div class="form-group row collapse" id="overtimeAdjustment">
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Overtime hours" aria-label="Overtime Amount" id="overtimeValidation" aria-describedby="Overtime Amount">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="checkbox" data-toggle="collapse" href="#studentLoan" id="studentCheck">
<label class="form-check-label" for="studentLoan">
Student loan repayment
</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="checkbox" data-toggle="collapse" href="#pensionPayment" id="pensionCheck">
<label class="form-check-label" for="pensionPayment">
Pension payment
</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="checkbox" data-toggle="collapse" href="#overtimeAdjustment" id="overtimeCheck">
<label class="form-check-label" for="overtimeAdjustment">
Overtime hours
</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-outline-primary" id="calculateAmount">Calculate</button>
</div>
</div>
</form>
Browser console display :
Controller action displaying json :
controller debugging with form data recieved from ajax
I have figured out the problem, it seems it was to do with the way JavaScript handles decimal values (IE it doesn't natively) combined with the way data was being entered from the input forms.
Explicitly converting the user input in Javascript using
parseFloat().toFixed()
Then passing the data to the controller via AJAX call seems to fix the issue but i am going to look into finding a way to calculate the data in another way.

view in mvc can not render html for the second time

when I try to render HTML in view for the second time the HTML not change and nothing happens it still as it aims calling the same view two times when the modal is empty and when I fill modal with data and then try to render it
this is the view
<section class="col-12 m-b-60">
<h2 class="m-b-20">Deduction</h2>
<form class="form-inline">
<div class="row">
<div class="col-6">
<div class="input-group">
<label class="input-text">
<span class="label">Employee ID</span>
<input type="text" placeholder="Employee ID ..."id="employeid">
</label>
<a class="btn btn-default" onclick="veiwemployee()">
Get
</a>
</div>
</div>
<div class="col-6">
<div class="input-group">
</div>
</div>
</div>
</form>
</section>
<section class="col-12 m-b-20">
`#if (Model != null)`
{
#await Html.PartialAsync("/Views/Home/View.cshtml", Model);
}
</section>
The action
public IActionResult EmployeeDeduction(int employeeID = 0)
{
Deduction deduction = new Deduction() ;
if (employeeID == 0) { }
else
{
ModelState.Clear();
deduction = _conn.GetEmployeByEmployeeID(employeeID);
}
return View("/Views/view.cshtml",deduction);
}
The Js function
function veiwemployee() {
if ($("#employeid").val() == "") {
$("#employeid").style.borderColor = "red";
}
else {
$.ajax({
type: 'POST',
url: '/Home/EmployeeDeduction?employeeID=' + $("#employeid").val(),
async: false,
dataType: 'json',
success: function (resp) {
}
});
}
}
this tag does not have closing.
<input type="text" placeholder="Employee ID ..." id="employeid">
"/" missing

HTTP Post 400 (Bad Request) After DropDownList

My program is basically for technicians to key in their service report after they've fixed a computer.
I have one feature that allows them to create a new report and a part of the report is keying in the customer's name or in other words, the company's name.
I was first struggling to make a dropdownlist so that the technicians get easily pick the name of a customer that is already in the server. I gave up for a while and decided to put a normal
<input type="text"/>
and when I did a post method, everything worked fine.
However, after having succeeded at making a dropdownlist for the customers' names, I could not do a POST method any more due to a POST 400 (Bad Request). I checked the developer tools and noticed that instead of the name of the customer, it just inserted 'Object'.
My question is, will someone please point me in the right direction? I've been scratching my head the whole morning and I just can't figure out why.
CreateReport.cshtml
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section scripts {
#Scripts.Render("~/bundles/app")
}
<div class="page-header">
<h1>Add New Report</h1>
</div>
<br>
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Create New Report</h2>
</div>
<div class="panel-body">
<form class="form-horizontal" data-bind="submit: addReport">
<div class="form-group">
<label for="inputCustName" class="col-sm-2 control-label">Customer's Name</label>
<div class="col-sm-12">
<select data-bind="options:customers, optionsText: 'Name', value: newReport.CustomerName"></select>
<span data-bind="value"
</div>
</div>
<div class="form-group" data-bind="with: newReport">
<label for="inputRepId" class="col-sm-2 control-label">Report Id</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="inputRepId" data-bind="value:Id" />
</div>
<br>
<label for="inputDate" class="col-sm-2 control-label">Date</label>
<div class="col-sm-12">
<input type="date" class="form-control" id="inputDate" data-bind="value:Date" />
</div>
<br>
<label for="inputWarranty" class="col-sm-2 control-label">Warranty</label>
<div class="col-sm-12">
<input type="radio" name="Warranty" value="true" data-bind="checked:Warranty">Yes
<br>
<input type="radio" name="Warranty" value="false" data-bind="checked: Warranty">No
</div>
<br>
<label for="inputNature" class="col-sm-2 control-label">Nature of Service</label>
<div class="col-sm-12">
<input type="radio" name="ServiceNature" value="Installation" data-bind="checked:ServiceNature">Installation <input type="radio" name="ServiceNature" value="Repair" data-bind="checked:ServiceNature">Repair
<br>
<input type="radio" name="ServiceNature" value="Terminate" data-bind="checked:ServiceNature">Terminate <input type="radio" name="ServiceNature" value="Maintenance" data-bind="checked:ServiceNature">Maintenance
</div>
<br>
<label for="inputLabCost" class="col-sm-2 control-label">labour Charge</label>
<div class="col-sm-12">
<input type="number" class="form-control" id="inputLabCost" data-bind="value:LabourCharge" />
</div>
<br>
<label for="inputMatCost" class="col-sm-2 control-label">Material Cost</label>
<div class="col-sm-12">
<input type="number" class="form-control" id="inputMatCost" data-bind="value:TotalMaterial" />
</div>
<br>
<label for="inputTransport" class="col-sm-2 control-label">Transport</label>
<div class="col-sm-12">
<input type="number" class="form-control" id="inputTransport" data-bind="value:Transport" />
</div>
<br>
<label for="inputTotal" class="col-sm-2 control-label">Total</label>
<div class="col-sm-12">
<input type="number" class="form-control" id="inputTotal" data-bind="value:Total" />
</div>
<br>
<label for="inputComments" class="col-sm-2 control-label">Comments</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="inputComments" data-bind="value:Comments" />
</div>
<br>
<label for="inputCusId" class="col-sm-2 control-label">Customer's ID</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="inputCusId" data-bind="value:CustomerId" />
</div>
<br>
<label for="inputEngId" class="col-sm-2 control-label">Engineer's ID</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="inputEngId" data-bind="value:UserId" />
</div>
<br>
<!--
<script>
function myFunction() {
var y = document.getElementById("inputMatCost").value;
var z = document.getElementById("inputTransport").value;
var x = +y + +z;
document.getElementById("inputTotal").value = x;
}
</script>
-->
<!-- <select id="CustomerDropDown"></select> -->
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
<!-- This is using bootstrap modal component. This replace the simple native javascript alert as Selenium (Assignment 2) has problem detecting native javascript alert and therefore unable to do recording correctly
It is a bit longer but it also looks more presentatble as you can further style it if you like-->
<<div class="modal fade" tabindex="-1" role="dialog" id="reportAlert">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<p>New Report Has Been Successfully Added!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Back To Reports</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
app.js(script that the view is connected to)
var ViewModel = function () {
var self = this;
self.reports = ko.observableArray();
self.customers = ko.observableArray();
self.error = ko.observable();
self.detail = ko.observable();
self.newReport = {
Id: ko.observable(),
CustomerName: ko.observable(),
Date: ko.observable(),
Warranty: ko.observable(),
ServiceNature: ko.observable(),
LabourCharge: ko.observable(),
TotalMaterial: ko.observable(),
Transport: ko.observable(),
Total: ko.observable(),
Comments: ko.observable(),
CustomerId: ko.observable(),
UserId: ko.observable()
}
var reportsUri = 'http://localhost:64744/api/report/';
var customersUri = 'http://localhost:64744/api/customer/';
function ajaxHelper(uri, method, data) {
self.error(''); // Clear error message
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllReports() {
ajaxHelper(reportsUri, 'GET').done(function (data) {
self.reports(data);
});
}
function getCustomers() {
ajaxHelper(customersUri, 'GET').done(function (data) {
self.customers(data);
});
}
self.getReportDetail = function (item) {
ajaxHelper(reportsUri + item.Id, 'GET').done(function (data) {
self.detail(data);
});
}
//GET method, addReport
self.addReport = function (formElement) {
var report = {
Id: self.newReport.Id(),
CustomerName: self.newReport.CustomerName(),
Date: self.newReport.Date(),
Warranty: self.newReport.Warranty(),
ServiceNature: self.newReport.ServiceNature(),
LabourCharge: self.newReport.LabourCharge(),
TotalMaterial: self.newReport.TotalMaterial(),
Transport: self.newReport.Transport(),
Total: self.newReport.Total(),
Comments: self.newReport.Comments(),
CustomerId: self.newReport.CustomerId(),
UserId: self.newReport.UserId()
};
ajaxHelper(reportsUri, 'POST', report).done(function (item) {
self.reports.push(item);
$('#reportAlert').modal('show');
});
}
$('#reportAlert').on('hidden.bs.modal', function (e) {
window.location = "ReportInfo";
})
//DELETE METHOD deleteReportMethod
self.deleteReport = function (item) {
ajaxHelper(reportsUri + item.Id, 'DELETE').done(function (data) {
//just to inform the user that delete has been performed
$('#deleteRepAlert').modal('show');
});
}
// jquery event to detect when the user dismiss the modal.... to redirect back to the home page
$('#deleteRepAlert').on('hidden.bs.modal', function (e) {
window.location = "ReportInfo";
})
// Fetch the initial data.
getAllReports();
getCustomers();
};
ko.applyBindings(new ViewModel());
You are not telling Knockout what property holds the value to be stored in the options binding. I am guessing that the customers array holds complex objects. So you need to tell Knockout which property on those objects holds the value. If you want to store the Name property as the value as well:
<select data-bind="options:customers, optionsText: 'Name', optionsValue: 'Name', value: newReport.CustomerName"></select>
HTTP status 400 indicates that your parameter is wrong. Maybe parameter type or parameter name

Categories

Resources