Razor Pages Display Validation for Hidden Input - asp.net-core

I am attempting to provide user friendly input (as a percentage) for a decimal and be able to validate. I am stuck because the asp-validation-for will not display if the associated input is hidden.
Current technique is to use autonumeric.js for the client side formatting on a display only field that gets copied into the field to be saved to db.
How can I get validation message to display?
LoanEstimate.cs
[NotMapped]
public string RateDisplayOnly { get; set; }
[Range(0,1,ErrorMessage="Rate must be between 0.000% and 100.00%")]
[DisplayFormat(DataFormatString = "{0:p}")]
[Required]
public decimal? Rate { get; set; }
Create.cshtml
<div class="form-group">
<label asp-for="LoanEstimate.Rate" class="control-label"></label>
<input asp-for="LoanEstimate.RateDisplayOnly" class="form-control autonumeric-display-only autonumeric-percent" />
<input asp-for="LoanEstimate.Rate" class="form-control" type="hidden"/>
<span asp-validation-for="LoanEstimate.Rate" class="text-danger"></span>
</div>
Javascript
$(document).ready(function ($) {
//autonumeric.js field formatting
const anElement = AutoNumeric.multiple('.autonumeric-currency', {
currencySymbol: "$"
});
const anElement2 = AutoNumeric.multiple('.autonumeric-percent', {
decimalPlaces: 3,
rawValueDivisor: 100,
suffixText: "%"
}
)
$(".autonumeric-display-only").on('keyup', function () {
var str = this.id
var getThis = str.substring(0, str.indexOf("DisplayOnly"))
$("#" + getThis).val(AutoNumeric.getNumericString("#" + this.id));
});
});
ProblemValidation message does not display when input for LoanEstimate.Rate is hidden
Note: here is it displaying properly when not hidden

Use $.validator.setDefaults,here is a demo:
View:
<form method="post">
<div class="form-group">
<label asp-for="Rate" class="control-label"></label>
<input asp-for="RateDisplayOnly" class="form-control autonumeric-display-only autonumeric-percent" onblur="validateRate()"/>
<input asp-for="Rate" class="form-control" hidden />
<span asp-validation-for="Rate" class="text-danger"></span>
</div>
<input type="submit" value="submit" />
</form>
js:
function validateRate() {
$("#Rate").valid();
}
$.validator.setDefaults({
ignore: [],
// other default options
});
$(document).ready(function ($) {
//autonumeric.js field formatting
const anElement = AutoNumeric.multiple('.autonumeric-currency', {
currencySymbol: "$"
});
const anElement2 = AutoNumeric.multiple('.autonumeric-percent', {
decimalPlaces: 3,
rawValueDivisor: 100,
suffixText: "%"
}
)
$(".autonumeric-display-only").on('keyup', function () {
var str = this.id
var getThis = str.substring(0, str.indexOf("DisplayOnly"))
$("#" + getThis).val(AutoNumeric.getNumericString("#" + this.id));
});
});
result:

Related

how to get data from database using ajax asp.net core

According to the following codes i have created the Get Handler in Index Model
public IActionResult OnGetCustomer(CustomerSearchModel searchModel)
{
CustomerCombine combine = new CustomerCombine
{
MyViewModels = _customerApplication.GetAll(searchModel)
};
return Partial("./Customer", combine);
}
and this is my Razor View:
#model CustomerCombine
<form asp-page="./Index" asp-page-handler="Customer"
method="get"
data-ajax="true"
data-callback=""
data-action="Refresh"
>
<div class="form-group">
<input asp-for="#Model.MySearchModel.FullName" class="form-control " placeholder="search..." />
</div>
<button class="customer-submit btn btn-success" type="submit">جستجو</button>
</form>
<table>
#foreach (var item in #Model.MyViewModels)
{
<tr>
<td>#item.Id</td>
<td>#item.FullName</td>
<td>#item.Mobile</td>
<td>#item.Email</td>
<td>#item.Address</td>
<td>#item.Image</td>
</tr>
}
</table>
My modal is displayed successfully,and i can see my database's data, but when i fill search field and click on search button , nothing happens
can any one help me plz?:)
and this is my jquey codes: i dont anything about Jquery and these codes were ready and now i dont knoe how i should use from it
$(document).on("submit",
'form[data-ajax="true"]',
function (e) {
e.preventDefault();
var form = $(this);
const method = form.attr("method").toLocaleLowerCase();
const url = form.attr("action");
var action = form.attr("data-action");
if (method === "get") {
const data = form.serializeArray();
$.get(url,
data,
function (data) {
CallBackHandler(data, action, form);
});
} else {
var formData = new FormData(this);
$.ajax({
url: url,
type: "post",
data: formData,
enctype: "multipart/form-data",
dataType: "json",
processData: false,
contentType: false,
success: function (data) {
CallBackHandler(data, action, form);
},
error: function (data) {
alert("خطایی رخ داده است. لطفا با مدیر سیستم تماس بگیرید.");
}
});
}
return false;
});
});
function CallBackHandler(data, action, form) {
switch (action) {
case "Message":
alert(data.Message);
break;
case "Refresh":
if (data.isSucceced) {
window.location.reload();
} else {
alert(data.message);
}
break;
case "RefereshList":
{
hideModal();
const refereshUrl = form.attr("data-refereshurl");
const refereshDiv = form.attr("data-refereshdiv");
get(refereshUrl, refereshDiv);
}
break;
case "setValue":
{
const element = form.data("element");
$(`#${element}`).html(data);
}
break;
default:
}
}
function get(url, refereshDiv) {
const searchModel = window.location.search;
$.get(url,
searchModel,
function (result) {
$("#" + refereshDiv).html(result);
});
}
1.The third parameter of $.get() is the success function.
2.There is no isSucceced property in your postback data. The postback data is the partial view html code. You need use $("xxx").html(data); to update the partial view code.
3.Model Binding binds the property by name, <input asp-for="#Model.MySearchModel.FullName"/> does not match the CustomerSearchModel searchModel.
public IActionResult OnGetCustomer(CustomerSearchModel MySearchModel)
Whole working demo and more details I have commented on the code pls check carefully:
Model
public class CustomerCombine
{
public List<MyViewModel> MyViewModels { get; set; }
public CustomerSearchModel MySearchModel { get; set; }
}
public class CustomerSearchModel
{
public string FullName { get; set; }
}
public class MyViewModel
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public string Image { get; set; }
}
View(Index.cshtml)
#page
#model IndexModel
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#Html.Partial("Customer",Model.CustomerCombine)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#section Scripts
{
<script>
$(document).on("submit",'form[data-ajax="true"]',function (e) {
e.preventDefault();
var form = $(this);
const method = form.attr("method").toLocaleLowerCase();
const url = form.attr("action");
var action = form.attr("data-action");
if (method === "get") {
const data = form.serializeArray();
$.get(url,data,function (data) {
console.log(data); //you can check the response data in Console panel
CallBackHandler(data, action, form);
});
} else {
var formData = new FormData(this);
$.ajax({
url: url,
type: "post",
data: formData,
enctype: "multipart/form-data",
dataType: "json",
processData: false,
contentType: false,
success: function (data) {
CallBackHandler(data, action, form);
},
error: function (data) {
alert("خطایی رخ داده است. لطفا با مدیر سیستم تماس بگیرید.");
}
});
}
return false;
});
//}); //remove this.......
function CallBackHandler(data, action, form) {
switch (action) {
case "Message":
alert(data.Message);
break;
case "Refresh":
$(".modal-body").html(data); //modify here....
break;
case "RefereshList":
{
hideModal();
const refereshUrl = form.attr("data-refereshurl");
const refereshDiv = form.attr("data-refereshdiv");
get(refereshUrl, refereshDiv);
}
break;
case "setValue":
{
const element = form.data("element");
$(`#${element}`).html(data);
}
break;
default:
}
}
function get(url, refereshDiv) {
const searchModel = window.location.search;
$.get(url,
searchModel,
function (result) {
$("#" + refereshDiv).html(result);
});
}
</script>
}
Partial View does not change anything
#model CustomerCombine
<form asp-page="./Index" asp-page-handler="Customer"
method="get"
data-ajax="true"
data-callback=""
data-action="Refresh"
>
<div class="form-group">
<input asp-for="#Model.MySearchModel.FullName" class="form-control " placeholder="search..." />
</div>
<button class="customer-submit btn btn-success" type="submit">جستجو</button>
</form>
<table>
#foreach (var item in #Model.MyViewModels)
{
<tr>
<td>#item.Id</td>
<td>#item.FullName</td>
<td>#item.Mobile</td>
<td>#item.Email</td>
<td>#item.Address</td>
<td>#item.Image</td>
</tr>
}
</table>
PageModel
public IActionResult OnGetCustomer(CustomerSearchModel MySearchModel)//change here....
{
CustomerCombine combine = new CustomerCombine
{
MyViewModels = _customerApplication.GetAll(searchModel) //be sure here contains value...
};
return Partial("./Customer", combine);
}
Result:

How to send upload file to controller - files is always empty

UserAdmin.cshtml
<div class="modal-body">
<form id="upload-file-dialog-form"
class="needs-validation form-group" novalidate
onsubmit="UploadFile()"
enctype="multipart/form-data"
method="post">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="file_Uploader" />
</div>
<div class="form-group">
<div class="col-md-10 modal-footer">
<input type="submit" class="btn btn-primary" value="Upload"/>
</div>
</div>
</form>
</div>
UserAdmin.js
function UploadFile() {
var form = $('form')[0];
var formData = new FormData(form);
console.log(formData);
$.ajax({
url: '/API/Upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (data) {
},
error: function () {
}
});
}
Controller
[HttpPost]
public async Task<IActionResult> Upload(List<IFileUpload> files)
{
try
{
var check = (HttpContext.Request.Form.Files);
long size = files.Sum(f => f.Length);
//some code removed
return Ok(new { count = files.Count, size, filePaths });
}
catch (Exception exc)
{
logger.Error("Error in upload() " + exc.Message);
throw;
}
}
the files in controller is always 0.
If onsubmit="UploadFile()" is replaced with
asp-controller="API" asp-action="Upload"
then I get something in check but again converting it to List of IFileUpload is another blocker
First of all, If you want to upload multiple files you have to add multiple="multiple" in your input. FormData will be empty if you print it like this, you have to iterate through the items.
<input type="file" name="file_Uploader" multiple="multiple" />
Please follow the codes below, I tested it working.
Complete form
<form id="upload-file-dialog-form"
onsubmit="UploadFile(event)">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="file_Uploader" multiple="multiple" />
</div>
<div class="form-group">
<div class="col-md-10 modal-footer">
<input type="submit" class="btn btn-primary" value="Upload" />
</div>
</div>
</form>
Construct form data like below
<script>
function UploadFile(e) {
e.preventDefault();
var formData = new FormData($('#upload-file-dialog-form')[0]);
$.each($("input[type='file']")[0].files, function(i, file) {
formData.append('files', file);
});
$.ajax({
url: '/API/Upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
},
error: function() {
}
});
}
</script>
Action method
[HttpPost]
public async Task<IActionResult> Upload(List<IFormFile> files)
{
try
{
var check = (HttpContext.Request.Form.Files);
long size = files.Sum(f => f.Length);
return Ok(new { count = files.Count, size });
}
catch (Exception exc)
{
_logger.LogWarning("Error in upload() " + exc.Message);
throw;
}
}
In model class, use IFormFile
public List<IFormFile> file_Uploader {get;set;}"
In controller, change the parameter like this
public async Task<IActionResult> Upload(List<IFormFile> file_Uploader)
add multiple to upload more files, and keep the name attribute the same as parameter to post value, code like below:
<input type="file" name="file_Uploader" multiple/>
result:

Adding İtems in Shopping cart

I've been working on my shopping cart program, but I keep having problems with adding an item to the shopping cart
here is my code;
HomeController class
[HttpPost]
public ActionResult AddToBasket(int id)
{
var basketJson = HttpContext.Session.GetString(SESSION_KEY);
List<SepetProduct> sepet;
if (basketJson == null)
{
sepet = new List<SepetProduct>();
}
else
{
sepet = JsonSerializer.Deserialize<List<SepetProduct>>(basketJson);
}
if (sepet.Any(x=> x.id == id))
{
sepet.Single(x => x.id == id).Toplam++;
}
else
{
sepet.Add(new SepetProduct { id = id, Toplam = 1 });
}
basketJson = JsonSerializer.Serialize(sepet);
HttpContext.Session.SetString(SESSION_KEY, basketJson);
return Json(new { status = true, Msg = "Ürün Sepete Eklendi", Data = sepet });
}
'''
and here is my Button action code
<form action="#Url.Action("addToBasket","Home")" method="post" enctype="multipart/form-data">
<input type="hidden" name="Id" value="#urun.UrunId" />
<button type="submit" class="btn btn-dark">
<span class="fa fa-shopping-cart"></span>Sepete ekle
</button>
</form>
The problem is that, when ı press to "sepete ekle" button, item was added to cart, but it directs us to a new page called "https://localhost:44302/Home/addToBasket"
and show us those data
'''
status true
msg "Ürün Sepete Eklendi"
data
0
id 2
toplam 1
'''
I would like to when ı press to 'sepete ekle ' button, the page remains the same, but the product is added to the basket. it just shows us a message saying added.
How can ı do that. thank you for interesting and helping
You can try to use ajax to replace form post.Here is a working demo:
TestBasket.cshtml(I use value="1" to test.And add id="Id" to hidden input.Also,I need to change the type of button,so that when click it,it will not submit form,it will go to submitData() function.):
<form action="#Url.Action("addToBasket","Home")" method="post" enctype="multipart/form-data">
<input type="hidden" id="Id" name="Id" value="1" />
<button type="button" onclick="submitData()" class="btn btn-dark">
<span class="fa fa-shopping-cart"></span>Sepete ekle
</button>
</form>
<script>
function submitData() {
$.ajax({
type: "POST",
url: '#Url.Action("addToBasket","Home")',
data: { "id": $("#Id").val() }
}).done(function (data) {
console.log(data.msg);
});
}
</script>
HomeController:
public IActionResult TestBasket()
{
return View();
}
[HttpPost]
public ActionResult AddToBasket(int id)
{
return Json(new { status = true, Msg = "Ürün Sepete Eklendi", Data = new List<SepetProduct>() });
}
result:

asp.net core: how to apply a ModelState error when a form is submitted via AJAX

I am trying to display the errors associated with a form.
The form has a validation performed on the client (works fine) and on the server (that's my issue). The actual submission code is done through an ajax call:
$.ajax({
type: "POST",
url: url,
dataType: "text",
data: fiscalYearData,
success: function () {
showSuccess('Saved successfully');
closeForm();
},
error: function (error) {
showError('An error occured');
}
});
Unfortunately, that is not satifying. In my controller, I'm returning a ModelSatte with all relevant errors provided:
if (ModelState.ErrorCount > 0)
return BadRequest(ModelState);
// save the modified entity
await fiscalYearService.SaveFiscalYearAsync(fy, SecurityContext);
return Ok();
How can I modify the ajax error handling function to use the ModelState to display the error in the form itself?
Edit I apparently need to clarify what I would like to do:
I receive a ModelState containing errors error back from the ajax call. I would like to display these errors in the form in the same way they would have been displayed if I had submitted the form via a form submit button and page refresh: fields corresponding tot the error's keys should be marked in red with the corresponding error text displayed in the appropriate error labels.
You can pass ModelState error message to ajax,and put error.responseText into form.
Action:
if (ModelState.ErrorCount > 0) {
//Customize your error message
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => !string.IsNullOrWhiteSpace(x.ErrorMessage) ? x.ErrorMessage : x.Exception.Message.ToString()));
return BadRequest(messages);
}
ajax:
$.ajax({
type: "POST",
url: url,
dataType: "text",
data: fiscalYearData,
success: function () {
showSuccess('Saved successfully');
closeForm();
},
error: function (error) {
showError(error.responseText);
}
});
Update:
If you want to validate like form post,I think you don't need to use ModelState,you can use $("#xxform").valid() in js.So that only when the model is valid,we will use ajax to post data to action.Here is a demo:
Model:
public class TestModelState {
[Required]
public string FirstName { get; set; }
[Required]
public string MiddleName { get; set; }
[Required]
public string LastName { get; set; }
}
View:
<form id="myform" method="post">
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="MiddleName" class="control-label"></label>
<input asp-for="MiddleName" class="form-control" />
<span asp-validation-for="MiddleName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<input type="submit" value="submit" />
</form>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script>
$('#myform').submit(function (e) {
e.preventDefault();
// check if the input is valid using a 'valid' property
if ($("#myform").valid()) {
$.ajax({
type: "POST",
url: "/Test1/TestModelState",
data: $("#myform").serialize(),
success: function (data) {
//showSuccess('Saved successfully');
//closeForm();
},
error: function (error) {
//console.log(error.responseText);
}
});
}
})
</script>
result:

Watin. how to show invinsible class

HTML code:
<div class="col-sm-9">
<input name="NewCardOrAccountNumber" class="form-control ui-autocomplete-input" id="NewCardOrAccountNumber" type="text" value="" autocomplete="off">
<span class="ui-helper-hidden-accessible" role="status" aria-live="polite"></span>
</div>
<div class="unvisible" id="clientInfoNew">
<div class="form-group">
<label class="col-sm-3 control-label">FIRST NAME</label>
<div class="col-sm-9" id="FnameNew"></div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">LAST NAME</label>
<div class="col-sm-9" id="LnameNew"></div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">BIRTH DATE</label>
<div class="col-sm-9" id="BirthDateNew"></div>
</div>
Watin code:
[TestMethod]
[TestCategory("Rimi Change card page")]
public void Rimi_4444_Change_Card_and_Assert()
{
//Web Address
using (IE ie = new IE(this.Rimi))
{
//IE ie = new IE(RimiChangeCard);
ie.BringToFront();
ie.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.Maximize);
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
If I write card number from keyboard, the invisible class appear, and you can see FIRST NAME, LAST NAME and so on. But if I do this with watin, it does not appear, and you only see card number which you input. Its like hidden fields of information. I do not know how to make that I could see this fields when I input card number.
There would be a JavaScript function, which gets executed when you manually enter the data in the text field.Go through the Java Script functions on the same page which refer to that element using it's ID NewCardOrAccountNumber.
Refer to this link for sample application. Where msg_to is element, and has a KeyUp event associated. When that filed gets a , value, there is a div section inside which a `Subject' field is shown.
Similarly, after executing the TypeText, try to trigger related event mentioned in the Java Script event using Java script execution.
EDIT: I see that the javascript functions gets executed after bulr event is fired. This means the textbox field should loose the focus. Try the below options.
// 1. Try focusing out of control.
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
ie.TextField(Find.ById("OldCardOrAccountNumber")).Click();
ie.WaitForComplete();
// 2. Try Using Send Keys method to tab out.
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
System.Windows.Forms.SendKeys.SnedWait("{TAB}"); // Need to add System.Windows.Forms reference to the project.
I put image on the internet, so click on this link Image and you will see on first image how look page, second picture - what have to happen when you input card number (from keyboard), third - what happen when card namuber is input from watin (does not appear information about card).
HTML code:
<div class="ibox-content">
<br>
<div class="form-horizontal">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label class="col-sm-3 control-label">NEW CARD</label>
<input name="NewCardId" id="NewCardId" type="hidden" value="0" data-val-required="The NewCardId field is required." data-val-number="The field NewCardId must be a number." data-val="true">
<div class="col-sm-9"><span class="ui-helper-hidden-accessible" role="status" aria-live="polite"></span><input name="NewCardOrAccountNumber" class="form-control ui-autocomplete-input" id="NewCardOrAccountNumber" type="text" value="" autocomplete="off"></div>
</div>
<div class="unvisible" id="clientInfoNew">
<div class="form-group">
<label class="col-sm-3 control-label">FIRST NAME</label>
I maybe find what you looking for Sham, but I do not know how to use it :
<script type="text/javascript">
$(document).ready(function() {
var NewCardId = "#NewCardId";
var OldCardId = "#OldCardId";
var NewCardNumber = "#NewCardOrAccountNumber";
var OldCardNumber = "#OldCardOrAccountNumber";
$(NewCardNumber).autocomplete(
{
source: function(request, response) {
$.ajax({
url: '/LoyaltyWebApplication/Suggestion/GetCardSuggestions',
dataType: "json",
data: {
str: $(NewCardNumber).val()
},
success: function(data) {
response($.map(data, function(item) {
var label = "";
if (item.Fname != null) label += item.Fname;
if (item.Lname != null) label += " " + item.Lname;
if (label.trim() != '') label = " (" + label.trim() + ")";
return {
value: item.CardNumber,
label: item.CardNumber + label
}
}));
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
},
select: function(event, ui) {
getCardDetails($(NewCardNumber), $(NewCardId), 'newCardSegments', true);
$("#newCardSegments").hide();
$("#clientInfoNew").show();
},
minLength: 2
}).blur(function() {
getCardDetails($(NewCardNumber), $(NewCardId), 'newCardSegments', true);
});
$(OldCardNumber).autocomplete(
{
source: function(request, response) {
$.ajax({
url: '/LoyaltyWebApplication/Suggestion/GetCardSuggestions',
dataType: "json",
data: {
str: $(OldCardNumber).val()
},
success: function(data) {
response($.map(data, function(item) {
var label = "";
if (item.Fname != null) label += item.Fname;
if (item.Lname != null) label += " " + item.Lname;
if (label.trim() != '') label = " (" + label.trim() + ")";
return {
value: item.CardNumber,
label: item.CardNumber + label
}
}));
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
},
select: function(event, ui) {
getCardDetails($(OldCardNumber), $(OldCardId), 'oldCardSegments', false);
$("#oldCardSegments").hide();
},
minLength: 2
}).blur(function() {
getCardDetails($(OldCardNumber), $(OldCardId), 'oldCardSegments', false);
});
function getCardDetails(cardNumHolder, cardIdHolder, segmentTablePlace, isNew) {
$.getJSON('/LoyaltyWebApplication/LOV/SetId?lovType=ReplacementLOV&lovValue=' + cardNumHolder.val(), null,
function(data) {
$("#clientInfo" + ((isNew) ? "New" : "Old")).show();
if (cardNumHolder.val() == '') {
return;
}
var i;
for (i = 0; i < data.otherNames.length; i++) {
$("#" + data.otherValues[i] + (isNew ? "New" : "Old")).text(data.otherNames[i]);
}
cardIdHolder.val(data.Id);
$.getJSON('/LoyaltyWebApplication/Replacement/ClientSegmentsList?clientId=' + data.Id + "&no_cache=" + Math.random, function(data) {
$("#" + segmentTablePlace).find('tbody').empty();
if (data.length > 0) {
$.each(data, function(index) {
$("#" + segmentTablePlace).find('tbody').append("<tr><td>" + data[index].SegmentCode + "</td><td>" + data[index].SegmentName + "</td></tr>");
});
$("#" + segmentTablePlace).show();
}
});
});
}
$("#resetVal").click(function() {
$("#NewCardOrAccountNumber").attr("value", "");
$("#NewCardOrAccountNumber").val("");
$("#NewCardId").attr("value", "");
$("#NewCardId").val("");
$("#clientInfoNew").hide();
$("#OldCardOrAccountNumber").attr("value", "");
$("#OldCardOrAccountNumber").val("");
$("#OldCardId").attr("value", "");
$("#OldCardId").val("");
$("#clientInfoOld").hide();
return false;
});
});
</script>