Returning error message using SweetAlert - c#

In AccountController, I notice that the sample registration code catches UserFriendlyException and returns the error message in the ViewBag.
How can I return it from a SweetAlert?
[HttpPost]
public virtual async Task<ActionResult> Register(RegisterViewModel model)
{
try
{
// Code omitted for brevity
}
catch (UserFriendlyException ex)
{
ViewBag.ErrorMessage = ex.Message; // I need to return this using SweetAlert
return View("Register", model);
}
}
html code
<form action="javascript:;" id="register-form" class="login-form" method="post">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>Enter required fields. </span>
</div>
#if (#ViewBag.ErrorMessage != null)
{
<div class="alert alert-danger">
<i class="fa fa-warning"></i> #ViewBag.ErrorMessage
</div>
<script>abp.message.error("#ViewBag.ErrorMessage");</script>
<input type="hidden" value=" #ViewBag.ErrorMessage" id="hf_error" >
}
<div class="row">
<div class="col-xs-12">
<input type="text" class="form-control form-control-solid placeholder-no-fix form-group" autocomplete="off" name="name" placeholder="#L("Name")" required autofocus id="name">
</div>
<div class="col-xs-12">
<input class="form-control form-control-solid placeholder-no-fix form-group" type="text" autocomplete="off" placeholder="#L("Surname")" name="surname" required id="surname" />
</div>
<div class="col-xs-12">
<input type="password" class="form-control form-control-solid placeholder-no-fix form-group" autocomplete="off" name="password" placeholder="#L("Password")" required autofocus id="password">
</div>
</div>
<div class="row">
<div class="col-sm-6 text-left">
<div class="forgot-password" style="margin-top: 5px;">
Login To Your Account
</div>
</div>
<div class="col-sm-6 text-right">
<button class="btn green" id="btnSubmit" type="submit">Register</button>
</div>
<hr />
</div>
</form>
jquery function below
var jsonObject = {
Name: name,
Surname: surname,
//EmailAddress: email,
// UserName: username,
Password: password
};
abp.ajax({
url: abp.appPath + 'Account/Register',
type: 'POST',
data: JSON.stringify(jsonObject)
}).done(function(data) {
alert("done");
}).fail(function(data) {
alert("fail");
});

Since that method returns a View result, it makes sense to use ViewBag for the error message.
To show a SweetAlert, add the following in #section Scripts in Register.cshtml:
#section Scripts {
// ...
#if (ViewBag.ErrorMessage != null)
{
<script>abp.message.error("#ViewBag.ErrorMessage");</script>
/*<script>swal("#ViewBag.ErrorMessage", "", "error");</script>*/
}
}
Both <script> tags trigger identical popups.

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

why does my page always redirects to the actionmethod view which doesnt exist rather than return to the view from where the actionmethod was called

I have a modal form that has a submit button already. Now I want to do a server-side validation for one of the data on the form. this validation will is meant to return a response to the user on the modal form if the data exist or not.
I am using an HTML action link to call an action method with ajax.
<div class="modal-body">
#using (Html.BeginForm("CreateSchool", "School", FormMethod.Post, new { enctype = "multipart/form-data", #class = "modal-form", id = "createSchoolForm" }))
{
#Html.AntiForgeryToken()
<div class="row forms">
<div class="form-group col-xs-12">
<label class="control-label col-xs-12" for="createSchool_Name">
School Name <span class="text-danger">*</span>
</label>
<input type="text" class="form-control col-xs-10" name="Name" id="createSchool_Name" />
</div>
<div class="form-group col-xs-12">
<label class="control-label col-xs-12" for="image">
School Logo
</label>
<div class="col-md-10">
<input type="file" accept="image/*" name="image" id="createSchool_image" />
<img id="img-header-create" class="img-responsive" style="height: 100px;" />
</div>
</div>
<div class="form-group col-xs-12">
<label class="control-label col-xs-12" for="createSchool_Email">
Contact Email <span class="text-danger">*</span>
</label>
<input type="text" name="ContactEmail" class="form-control col-xs-12" id="createSchool_Email" />
</div>
<div class="form-group col-xs-12">
<label class="control-label col-xs-12" for="createSchool_Number">
Contact Number <span class="text-danger">*</span>
</label>
<input type="text" name="ContactNumber" class="form-control col-xs-12" id="createSchool_Number" />
</div>
<div class="form-group col-xs-12">
<label class="control-label col-xs-4" for="createSchool_Subdomain">
School Subdomain <span id="domainspan"></span>
</label>
#Html.ActionLink("Check if Sub-Domain is available", "CheckDomain", null, new { #class = "col-xs-3", id = "CheckDomain" })
<p id="subdomainresult" class="col-sm-3">me</p>
#*<input type="submit" id="CheckDomain" name="CheckDomain" value="Check Sub Domain" class=" text-uppercase" />*#
#*<input id="CheckDomain_submit"> Check SubDOmain</input>*#
<input type="text" name="Subdomain" class="form-control col-xs-12" id="createSchool_Subdomain" />
</div>
<div class="form-group col-xs-12" style="margin-bottom: 25px;">
<label class="control-label col-xs-12" for="createSchool_StudentsCanEnrollForModules">
Students Are Allowed To Enroll For Modules (Learn More)
</label>
<div class="col-xs-10">
<div class="forms__checkbox">
<input type="checkbox" name="StudentsCanEnrollForModules" class="checkbox" id="createSchool_StudentsCanEnrollForModules" checked />
</div>
</div>
</div>
<div class="form-group col-xs-12" style="margin-bottom: 25px;">
<label class="control-label col-xs-12" for="createSchool_PrivateSchool">
This is a Private School (Learn More)
</label>
<div class="col-xs-10">
<div class="forms__checkbox">
<input type="checkbox" name="PrivateSchool" class="checkbox" id="createSchool_PrivateSchool" />
</div>
</div>
</div>
<div class="form-group col-xs-12">
<label class="control-label">
Description
</label>
#*<textarea type="text" name="Description" class="form-control col-xs-12" id="createSchool_Description"></textarea>*#
<div id="createSchool_Description_div" style="height:300px;"></div>
</div>
<div class="form-group col-xs-12">
<input type="button" id="createSchool_submit" value="Create" class="btn btn-success text-uppercase" />
<button type="button" class="btn btn-default text-uppercase" data-dismiss="modal">Close</button>
<img class="preloader_image" style="height: 30px" src="~/images/loadingicon_large.gif" />
</div>
</div>
}
</div>
This is my jquery ajax code that calls the action method to validate the user input
$("#CheckDomain").click(function () {
debugger;
var sch = new Object();
sch.SubDomain = $('#createSchool_Subdomain').val();
if (sch != null) {
$.ajax({
url: "/School/CheckDomain",
//url: "#Url.Action("CheckDomain", "School")",
type: "POST",
data: JSON.stringify(sch),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
debugger;
if (response != null) {
switch (response) {
case true:
//$("#subdomainresult").html("Submdomain already exists ");
alert("Submdomain already exists " );
break;
case false:
alert("Submdomain is available ");
//$("#subdomainresult").html("Submdomain is available ");
break;
default:
}
} else {
alert("Please enter a subdomain to check availability");
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
});
this is my action method
[HttpPost]
public ActionResult CheckDomain(CreateSchoolViewModel sch)
{
string SubDomain= sch.Subdomain;
if (!string.IsNullOrWhiteSpace(SubDomain))
{
var IsSubdomianAvailable = Util.getSchoolFromSubdomain(databaseHandler, SubDomain);
if (IsSubdomianAvailable == null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
return Json(null, JsonRequestBehavior.AllowGet);
}
the page always tries to redirect to the action name( checkdomian) view rather than remain on the page
This line
#Html.ActionLink("Check if Sub-Domain is available", "CheckDomain", null, new { #class = "col-xs-3", id = "CheckDomain" })
can be replaced with a link with href set to javascript:void(0)
<a id='CheckDomain' href='javascript:void(0)' class='col-xs-3'>Check if Sub-Domain is available</a>
The link can be void, since there is a JQuery click event handler attached to it.

ReactJS.Net Server Side Rendering Not Initializing Handlers

New to reactjs.net. I did my best to follow the instructions on the https://reactjs.net/guides/server-side-rendering.html website but i am still getting the following reference error re: my component: Signup is not defined. The page renders but the Signup component doesnt seem to be there. What am I doing wrong?
ReactConfig.cs:
public static void Configure()
{
ReactSiteConfiguration.Configuration
.AddScript("~/Scripts/jsx/welcome.jsx")
.AddScript("~/Scripts/jsx/navbar.jsx")
.AddScript("~/Scripts/jsx/login.jsx")
.AddScript("~/Scripts/jsx/Signup.jsx")
.AddScript("~/Scripts/jsx/about.jsx")
.AddScript("~/Scripts/jsx/contact.jsx");
}
SignUp.cshtml:
#{
ViewBag.Title = "Sign Up";
}
#Html.React("Signup", new { })
#section scripts{
#Scripts.Render("~/bundleSignUp")
#Html.ReactInitJavaScript()
}
class Signup extends React.Component {
constructor(props) {
super(props);
this._onSubmit = this._onSubmit.bind(this);
}
_onSubmit(e) {
console.log("HERE WE GO");
}
render() {
return (
<div>
<NavBar />
<form className="container container-fluid">
<div className="pullDown">
<div className="row">
<div className="col-lg-6 col-md-7 col-sm-8">
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email address</label>
<input type="email" className="form-control" id="exampleInputEmail1" placeholder="Enter email" ref="email" />
</div>
</div>
</div>
<div className="row">
<div className="col-lg-6 col-md-7 col-sm-8">
<div className="form-group">
<label htmlFor="exampleInputPassword1">Password</label>
<input type="password" className="form-control" id="exampleInputPassword1" placeholder="Enter Password" ref="passWd" />
</div>
</div>
</div>
<div className="row">
<div className="btn btn-success" onClick={this._onSubmit}>Submit</div>
</div>
</div>
</form>
</div>
);
}
}

The id is missed when form is posted to controller

I am developing a mvc website.I have a table called member .this table has a controller and the controller has an edit method as you can see :
public ActionResult Edit()
{
int userId = _memberRepository.ReturnMemberIdByMobile(User.Identity.Name);
ViewBag.Edit = _memberRepository.FindById(userId).First();
return View();
}
[HttpPost]
public ActionResult Edit(Member value)
{
try
{
if (_memberRepository.Edit(value))
{
value.RegisteredDate = DateTime.Now;
_memberRepository.Save();
TempData["Success"] = "با موفقیت ویرایش شد ...";
string strLocation = HttpContext.Server.MapPath("~/Image/users");
if (value.ImgByte != null)
{
value.ImgByte.SaveAs(strLocation + #"\" + value.Id + ".jpg");
}
}
}
catch (Exception)
{
TempData["Error"] = "ویرایش نشد، لطفاً مجدداً تلاش نمایید";
}
return RedirectToAction("Edit");
}
The edit view is correctly work.the problem is when i post my view to edit controller .the id of member is changed to 0 it means it is missed.why ?and the value can't be edited.
#using DCL
#{
ViewBag.Title = "Edit";
Layout = "~/Areas/user/Views/Shared/_shared.cshtml";
Member membervalue = new Member();
membervalue = ViewBag.Edit;
}
#using (#Html.BeginForm("Edit", "User", FormMethod.Post,
new {id = "form", enctype = "multipart/form-data"}))
{
if (TempData["Error"] != null)
{
<div class="pad margin no-print">
<div class="callout callout-info" style="margin-bottom: 0 !important; background-color: #ea0000 !important; border-color: #d20000">
#TempData["Error"]
</div>
</div>
}
if (TempData["Information"] != null)
{
<div class="pad margin no-print">
<div class="callout callout-info" style="margin-bottom: 0 !important; background-color: orangered !important; border-color: red">
#TempData["Information"]
</div>
</div>
}
if (TempData["Success"] != null)
{
<div class="pad margin no-print">
<div class="callout callout-info" style="margin-bottom: 0 !important; background-color: #00A65A !important; border-color: #00925A">
#TempData["Success"]
</div>
</div>
}
<div class="row">
<!-- general form elements -->
<div class="col-xs-12">
<div class="box">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">حساب کاربری</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<div class="box-body">
<div class="col-lg-7">
<div class="input-group">
<label for="Name">نام</label>
<input class="form-control" id="Name" name="Name" type="text" value="#membervalue.Name">
</div>
<div class="input-group">
<label for="family">نام خانوادگی</label>
<input class="form-control" id="family" name="family" type="text" value="#membervalue.Family">
</div>
<div class="input-group">
<label for="mobile">موبایل</label>
<input class="form-control" id="mobile" name="mobile" type="text" value="#membervalue.Mobile">
</div>
<div class="input-group">
<label for="password">رمز عبور</label>
<input class="form-control" id="password" name="password" type="password" value="#membervalue.Password">
</div>
<div class="input-group">
<label for="Email">ایمیل</label>
<input class="form-control" id="Email" name="Email" type="text" value="#membervalue.Email">
</div>
<div class="form-group">
<label for="ImgByte">عکس </label>
<input id="ImgByte" name="ImgByte" type="file">
</div>
<input type="hidden" id="Id" name="id" value="#membervalue.Id">
</div>
</div>
<!-- /.box-body -->
</div>
</div>
</div>
<!-- /.box -->
</div>
<div class="row" style="margin: 0; margin-bottom: 20px">
<div class="box-footer" style="direction: ltr">
<button type="submit" class="btn btn-info">ویرایش</button>
<a class="btn btn-gray" href="#Url.Action("Index", "Home", null)">انصراف</a>
</div>
</div>
}
Instead of using the viewbag for your model you should pass in the model as a strongly typed object. You can do this with the following change in the Action. Then in your view define the model at the top and you can use it throughout the code.
You will also need a #Html.HiddenFor tag for your id. Now it is no longer possible (without a compile time exception that is) to create a type-o. On your previous code maybe you cased Id incorrectly which would cause it not to be populated OR maybe the form field name was not cased correctly. This takes all those manual errors out of the equation.
public ActionResult Edit()
{
int userId = _memberRepository.ReturnMemberIdByMobile(User.Identity.Name);
var model = _memberRepository.FindById(userId).First();
return View(model); // pass this in as the model, do not use viewbag
}
View
#model = Member #* namespace qualified type *#
#*... editor code *#
#Html.HiddenFor(x => x.Id)
#Html.TextboxFor(x => x.Name) #* do this instead of manual input *#
I ran your code, and there is no mistake in it. Id is passed correctly to Edit (post) action. The only reason it can be empty in the code that you show is that FindById returned entity without Id property set.

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