I want to pop up my div class that contains user at password text box but nothings happen and I test also my function if its running correctly that's why I put alert in my function. This my code bellow. I try so many solution and yet still not show my div. Can any give me a best solution regarding this matter or other way to pop up the web form without leaving my current page.
#model TBSWebApp.Models.User
#{
ViewBag.Title = "UserLogin";
Layout = "~/Layout/_webLayout.cshtml";
}
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<div>
<fieldset>
<div class="container">
<div class="row">
<div class="col-xs-12">
<button id="btnShowModal" type="button" class="btn btn-sm btn-default pull-left col-lg-11 button button4">
Sign-in
</button>
<div class="modal fade" tabindex="-1" id="loginModal" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">Satya Login</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<input class="form-control" type="text" placeholder="Login Username" id="inputUserName" />
</div>
<div class="form-group">
<input class="form-control" placeholder="Login Password" type="password" id="inputPassword" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Sign</button>
<button type="button" id="btnHideModal" class="btn btn-primary button button4">
Hide
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</fieldset>
</div>
<footer>
<p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">
©
<script>document.write(new Date().toDateString());</script>
</p>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
//$(document).ready(function () {
$("#btnShowModal").click(function () {
alert("test");
$("#loginModal").modal('show');
});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
// });
</script>
I already solved my problem
<script>
$(document).ready(function () {
$("#submitButton").click(function () {
if (($("#userNameTextBox").val() != "") && ($("#passwordTextBox").val() != ""))
$.ajax(
{
type: "POST", //HTTP POST Method
url: "UserLogin/UserLogin", // Controller/View
dataType: "text/html",
data:
{ //Passing data
UserID: $("#userNameTextBox").val(),
Password: $("#passwordTextBox").val(),
}
});
});
});
//$(document).ajaxStart(function () { $("#loadingImg").show(); });
//$(document).ajaxStop(function () { $("#loadingImg").hide(); });
</script>
Related
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);
}
I have a form that displays a persons title and name.It shows a lot more than that, but this is the bit I am asking about.
I have a person table.
If the user wants to change the person details, is it possible to open up a pop up modal form that lists all the persons in the person table, so that the user can either select an existing person, or insert a new person and when the user closes the pop up, the main form is populated with the selected/new persons details?
I am using ASP.NET Core MVC 5 and EF Core 5.
Any help or pointing to a tutorial would be a great help, thanks.
UPDATE -
I have tried the following -
I have created a modal partial view -
#model Person
<div class="modal fade" id="personModal" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="personModalLabel">Persons</h4>
<button type="button" class="close" data-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Create">
<table class="table table-bordered table-striped table-hover">
<tbody>
#foreach (var pers in ViewBag.PersonList)
{
<tr>
<td style="display:none">#pers.Id</td>
<td class="text-left">
<a asp-action="details" asp-controller="admin" asp-route-id="#pers.Id" title="Click to select vaccination centre">#pers.Title.Description</a><br />
</td>
<td class="text-left ">
#pers.Forename
</td>
<td class="text-left ">
#pers.Surname
</td>
</tr>
}
</tbody>
</table>
<br />
<div class="form-row">
<label asp-for="TitleId" class="control-label col-md-2">Title</label>
<div class="col-md-4 mb-2">
<select asp-for="TitleId" asp-items="#(new SelectList(ViewBag.TitleList, "Id", "Description"))" style=" width: 363px; height: 37px"></select>
<span asp-validation-for="TitleId" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<label asp-for="Forename" class="control-label col-md-2">Forename</label>
<div class="col-md-4 mb-2">
<input asp-for="Forename" class="form-control" maxlength="100" />
<span asp-validation-for="Forename" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<label asp-for="Surname" class="control-label col-md-2">Surname</label>
<div class="col-md-4 mb-2">
<input asp-for="Surname" class="form-control" maxlength="100" />
<span asp-validation-for="Forename" class="text-danger"></span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save</button>
</div>
</div>
</div>
</div>
I have added the following script to site.js -
$(function () {
var placeHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function(data) {
placeHolderElement.html(data);
placeHolderElement.find('.modal').modal('show');
})
})
placeHolderElement.on('Click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
placeHolderElement.find('.modal').modal('hide');
})
})
})
And the controller -
[HttpGet]
public IActionResult Create()
{
List<Person> personList = _personRepository.Persons.ToList();
ViewBag.PersonList = personList;
List<Title> titleList = _titleRepository.Titles.ToList();
ViewBag.TitleList = titleList;
Person pers = new Person();
return PartialView("_PersonModalPartial", pers);
}
[HttpPost]
public IActionResult Create(Person pers)
{
_personRepository.CreatePerson(pers);
List<Person> personList = _personRepository.Persons.ToList();
ViewBag.PersonList = personList;
List<Title> titleList = _titleRepository.Titles.ToList();
ViewBag.TitleList = titleList;
return PartialView("_PersonModalPartial", pers);
}
I call the modal with the the following in my main form -
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create")" >Insert</button>
The above code shows the modal and populates the table.
However nothing happens when you press save!?
UPDATE 2 -
I changed the button in the modal for to
input type="submit" value="Submit" name="Submit" class="btn btn-success float-right" id="SubmitForm" />
And then changed the form tag in my modal form to -
<form method="post" asp-controller="Admin" asp-action="Create">
That worked.
Now I am wondering how you can pass the id value of the model into the Modal form using the data-url part of the calling button?
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create")" >Insert</button>
You can use #Url.Action("Create",new { id=xxx}),here is a demo:
Html(I use "sss" as a sample data of id):
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create1",new { id="sss"})">
Insert
</button>
js:
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeHolderElement.html(data);
placeHolderElement.find('.modal').modal('show');
})
})
Controller:
public IActionResult Create1(string id) {
return Ok();
}
result:
Update:
If you want to use #Model.Id:
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create1",new { id=Model.Id})">
Insert
</button>
I want to delete a record from table and I sent CategoryId with this code:
Main view :
<a data-toggle="modal" data-target="#Deletemodal" onclick="Func_LoadPv('#item.CategoryId')" class="btn btn-danger btn-xs">delete</a>
function Func_LoadPv(Cid) {
$.get("/AdminPanel/Category/ShowPartialView?CategoryId=" + Cid, function (res) {
$("div.modal-body").append(res);
});
}
Controller :
public IActionResult ShowPartialView(Guid CategoryId)
{
return PartialView("_DeleteMainCategory", CategoryId);
}
How can I get this value that is sent from the controller to the partial Modal?
And the problem I have is that the modal only opens once ?
How can I get this value that is sent from the controller to the partial Modal?
You can specify a model for your partial view _DeleteMainCategory.cshtml, like below.
#model Guid
<h1>DeleteMainCategory Partial View</h1>
#*content here*#
<h2>#Model</h2>
the problem I have is that the modal only opens once
The following sample with testing data work well for me, you can check and compare it with yours.
<table>
<tbody>
#foreach (var item in Model)
{
<tr>
<td> #rowCount</td>
<td>#item.CategoryTitle</td>
<td>#item.IconCategory</td>
<td>
<a data-toggle="modal" data-target="#Deletemodal" title="delete"
class="btn btn-danger btn-xs" onclick="Func_LoadPv('#item.CategoryId')">delete</a>
</td>
</tr>
}
</tbody>
</table>
<div id="Deletemodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
#*modal body here*#
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section scripts{
<script>
function Func_LoadPv(Cid) {
$.get("/AdminPanel/Category/ShowPartialView?CategoryId=" + Cid, function (res) {
$("div.modal-body").html(res);
});
}
</script>
}
Test Result
I solved
Modal :
<div id="deletemodal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">delete category</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="bodyModal" class="modal-body">
</div>
</div>
</div>
JQuery :
function DeleteCategory(id) {
$.ajax({
url: "/AdminPanel/Category/DeleteCategory/" + id,
type: "Get",
data: {}
}).done(function (result) {
$('#deletemodal').modal('show');
$('#bodyModal').html(result);
});
}
Controller :
public IActionResult DeleteCategory(Guid? id)
{
return View();
}
[HttpPost]
public IActionResult DeleteCategory(Guid id)
{
_admin.DeleteMainCategory(id);
return RedirectToAction("ShowMainCategory", "Category");
}
Partial View :
<form asp-action="DeleteCategory" class="form-padding">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<h5 class="text-center">Are You Sure ?</h5>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-info waves-effect">delete</button>
<button type="button" class="btn btn-danger waves-effect"
data-dismiss="modal">
cancel
</button>
</div>
I have this code in my action
var singedUser = HttpContext.User.Identity.Name;
try
{
_purchaseService.PurchaseCard(singedUser, cardName);
}
catch
{
}
And I want this to open ONLY if the code enters the catch block
<div id="Modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Purchasing Card</h4>
</div>
<div class="modal-body">
<p>You have unsufficient funds!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
And here is my button
<a class="button btn btn-success"
asp-controller="Store" asp-action="Buy"
asp-route-data ="#card.Name">Buy (#card.Price coins)</a>
I would appreciate if someone would tell me how I can open this dialogue box in the same page only if the code enters the catch block
You can also use an ajax call to return the partial view and add it to the DOM. Setting up a modal to load a partial view is actually pretty straight forward :
Create partial view : _ModalContent.cshtml
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Purchasing Card</h4>
</div>
<div class="modal-body">
<p>You have unsufficient funds!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
Modify your Index page :
<a id="button1" class="button btn btn-success"
asp-controller="Store" asp-action="Buy"
asp-route-data ="#card.Name">Buy (#card.Price coins)</a>
<div id="myModal"></div>
#section Scripts{
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
$("#button1").on("click", function (e) {
$('#myModal').load(this.href, function () {
$('#Modal').modal({
keyboard: true
}, 'show');
});
return false;
});
});
</script>
}
Controller function :
public IActionResult buy(string data)
{
.....
{
return PartialView("_ModalContent");
}
}
I would pass a variable through the ViewBag on the controller/action. Something like this in the controller:
var singedUser = HttpContext.User.Identity.Name;
try
{
_purchaseService.PurchaseCard(singedUser, cardName);
}
catch
{
ViewBag.ShowModal = false;
}
Then toggle whether or not to trigger JQuery to show the Modal in the scripts section of the view:
#section Scripts{
<script>
#if(ViewBag.ShowModal == true){
#Html.Raw("$('#Modal').modal('show');");
}
</script>
}
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