Thousands separator with razor MVC and js - javascript

I'm trying to save number with thousands separator inside number field
1000 >> 1,000
100000 >> 10,000
2000.02 >> 2,000.02
i want to use js and jquery for this issue,
i want thousands separators become visible when the user is typing.
<div class="form-group">
<label class="control-label col-md-2" Sum</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Sum, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.Sum, "", new { #class = "text-danger" })
</div>
</div>
Any help?

You can try autoNumeric plugin. Basic init will do what you need:
$('#Sum').autoNumeric('init');
Check section:
The basics on getting autoNumeric() up and running with the initialize
'init' method and default settings: ...

Related

Value from JQuery populated field not binding to MVC model

I'm working on a project with ASP.NET MVC, using Razor. Once the form finishes loading on the page, I expect the user triggers .on ('change') in an input. Once this happens, an AJAX call is executed, returning the user's data, disabling and filling the inputs that are linked to the properties of a model that starts empty (when the page is loaded).
The data is filling up without problems, but when I send it back to the controller to be processed, the values that correspond to the inputs that were filled after the AJAX execution arrive as null.
<div class="form-label-group col-md-4 mb-3">
#Html.LabelFor(model => model.AttendeeName, new { #class = "upside-label", #for = "firstName" })
#Html.EditorFor(model => model.AttendeeName, new { htmlAttributes = new { #class = "form-control", #id = "firstName", #placeholder = Resources.ResourcesPerson.PlaceholderPersonName } })
#Html.LabelFor(model => model.AttendeeName, new { #class = "downside-label", #for = "firstName" })
<div class="text-danger">
#Html.ValidationMessageFor(model => model.AttendeeName)
</div>
</div>
I have tried the following without success:
$("input[name=AttendeeName]").attr('disabled', true);
$("input[name=AttendeeName]").val(data.AttendeeName).change()
Thank you for your assistance.
This is expected behaviour. disabled elements are not sent in form data.
If you still want those values to be sent, don't disable the fields. Possibly try readonly instead, assuming that you don't want users to edit the fields:
$('input[name="AttendeeName"]').prop('readonly', true);

How can I append a Razor value to a div using jQuery [duplicate]

I need to use jQuery to add some elements dynamically. So I looked up in the internet and I found this. It is nice and working when there is plain html elements inside single quotes. I need to use razor syntax with jQuery.
I understand that jQuery is user side and razor is server side. They cannot be combined together. I am asking here because I need to know how do i achieve this.
My not working jQuery is as follows:
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".btnPlus", function () {
var html = '<div class="form-group">'+
'#Html.LabelFor(model => model.transaction_item, "transaction_item", htmlAttributes: new { #class = "control-label col-md-2" })'+
'<div class="col-md-4">'+
'#Html.DropDownList("transaction_item", null, htmlAttributes: new { #class = "form-control" })'+
'#Html.ValidationMessageFor(model => model.transaction_item, "", new { #class = "text-danger" })'+
'</div>'+
'<div class="col-md-6"><input type="button" class="BtnPlus" value="+" /></div>'+
'</div>'
$("#trItem").append($(html))
};
});
My aim is similar to the tutorial - to add elements dynamically. Here I am adding a label and dropdown on the click of button. How do I achieve this?
You cannot add Razor elements using JQuery because, as you have stated, JQuery is a client side library and ASP.NET using Razor syntax is a server side scripting language.
If you want to add elements created using Razor syntax then add a hidden element to the page and use JQuery to add a clone of it to the DOM.
Something like this should give you an idea of what I mean:
#Html.DropDownList("transaction_item", null, htmlAttributes: new { #class = "form-control", #id = 'template-ddl' })
$("#trItem").append($('#template-ddl').clone());
You can create a partial page _MyPartial.cshtml in your Views Shared folder.
Then in your view reference add the reference to your scripts section
#section Scripts {
#Html.Partial("~/Views/Shared/_MyPartial.cshtml",Model);
}
Partial page: _MyPartial.cshtml
#model MyViewModel
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".btnPlus", function () {
var html = '<div class="form-group">'+
'#(Html.LabelFor(model => model.transaction_item, "transaction_item", htmlAttributes: new { #class = "control-label col-md-2" }))'+
'<div class="col-md-4">'+
'#(Html.DropDownList("transaction_item", null, htmlAttributes: new { #class = "form-control" }))'+
'#(Html.ValidationMessageFor(model => model.transaction_item, "", new { #class = "text-danger" }))'+
'</div>'+
'<div class="col-md-6"><input type="button" class="BtnPlus" value="+" /></div>'+
'</div>'
$("#trItem").append($(html))
};
</script>
It is best to avoid generating jQuery/Javascript code with Razor. For many reasons your Javascript/jQuery code is better off in separate files (VS debugging/script bundling etc)
Instead inject the templated HTML into a hidden part of the page. A dummy script block works great for this as the browser will just ignore an unknown script type:
<script id="template" type="text/template">
<div class="form-group">
#Html.LabelFor(model => model.transaction_item, "transaction_item", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.DropDownList("transaction_item", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.transaction_item, "", new { #class = "text-danger" })
</div>
<div class="col-md-6"><input type="button" class="BtnPlus" value="+" /></div>
</div>
</script>
You can see what is generated with your DOM inspector to ensure the correct attributes are present.
Then simply use that HTML from the template to add new buttons:
$("#trItem").append($('#template').html());
The only issue you need to resolve is any duplicate IDs and indexing for multiple items. I usually use raw HTML in the template (not Razor) and use placeholders for the various attributes that need renaming.
e.g.
<script id="template" type="text/template">
<div class="form-group">
<label for="{id}"/>

Fetching HTML textfield value using Javasctipt

I have a textfield which is NOT enclosed in a form. Using javascript I need to extract the textfield value. How can I do this ?
I am using C#-Razor in my front end.
HTML Razor Syntax : (Note: this textfield is not enclosed in a form, and I don't want it to be enclosed in a form)
<div class="form-group">
#Html.TextBoxFor(model => model.NAME, new { #class = "control-label col-md-12", placeholder = "Name" })
#Html.LabelFor(model => model.NAME, new { #class = "col-md-12 " })
#Html.ValidationMessageFor(model => model.NAME)
</div>
Javascript code
$(document).ready(function () {
$('#UseShipAddr').click(function () {
alert(document.getElementById("NAME"));
}
});
Output I get
[HTMLInputElement]
You are alerting the actual html element itself. You need to get the value like this:
document.getElementById("NAME").value

Model is null in Kendo UI MVC in Microsoft Edge and Internet Explorer

I am using jquery serializeObject to retrieve model binded textbox and dropdown values in my project. In chrome i get the value for both textbox and dropdown however in Microsoft Edge i am not getting any values for the model binded object. In the bottom code, the value of viewModel comes as null for both SupplierName and SelectedSearchType when I use Microsoft Edge however i get the entered value in Chrome.
Any clue why i am not getting any value in Microsoft Edge and IE?
<form id="formSupplierInvitation" class="form-horizontal">
<fieldset id="SupplierInvitation">
<p style="margin-bottom: 15px;">
<b>Please enter your search criteria: </b>
</p>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.SupplierName, new { #class = "col-sm-4 control-label" })
<div class="col-sm-8">
#Html.TextBoxFor(model => model.SupplierName, new { #class = "form-control", maxlength = 100, #data_toggle = "tooltip", #title = "Maximum length is 100", })
#Html.ValidationMessageFor(model => model.SupplierName, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group required">
#Html.Label("Search Type", new { #class = "col-md-3 col-sm-4 control-label" })
<div class="col-sm-8">
#Html.DropDownListFor(m => m.SelectedSearchType, new SelectList(Model.AllSearchTypeLists, "SearchTypeValue", "SearchTypeText"), new { #name = "DropDownSearchType", #class = "form-control", data_placeholder = "Choose Search Type..." })
</div>
</div>
</div>
</div>
<input id="btnSearch" type="submit" value="Search" class="btn btn-default" />
<div class="col-sm-12">
#(Html.Kendo().Grid<SupplierPortal.ViewModels.SupplierInvitationResponseViewModel>()
.Name("GridSupplierInvitation")
.Columns(columns =>
{
columns.Bound(e => e.SupplierNumber).Width("160px");
columns.Bound(e => e.SupplierName).Width("180px");
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.ServerOperation(false)
.Read(read => read.Action("GetSuppliers", "Admin").Data("GetSearchParameters")))
)
</div>
</fieldset>
</form>
<script type="text/javascript">
function GetSearchParameters() {
return {
viewModel: $("#SupplierInvitation").serializeObject()
};
}
$('#btnSearch').click(function (e) {
e.preventDefault();
$('#GridSupplierInvitation').data('kendoGrid').dataSource.read();
});
</script>
public JsonResult GetSuppliers([DataSourceRequest] DataSourceRequest dataRequest, SupplierInvitationRequestViewModel viewModel)
{
var responseViewModels = new List<SupplierInvitationResponseViewModel>();
string supplierName = viewModel.SupplierName;
string selectedSearchType = viewModel.SelectedSearchType;
return Json(responseViewModels.ToDataSourceResult(dataRequest));
}
Update #1: Followed this post and found this fix. I needed to add 'input' attribute.
Jquery Serialize not working only on IE
function GetSearchParameters() {
return {
viewModel: $("#SupplierInvitation input").serializeObject()
};
}
Update #2: Need to update on my previous update. The previous solution adding 'input' only works for input attributes. (obviousuly). If you have a dropdownlist like above which will get converted to 'select' html attribute, you won't be able to get the value for your dropdown. I believe you can go two ways(?) to solve this. First, read the values by their id, set the values in variable and send those values as individual parameters. e.g.
var supplierName = $("#SupplierName").val();
var selectedSearchType = $("#SelectedSearchType option:selected").val();
Secondly, use serializeObject and set the properties values in the serialized object.
var supplierName = $("#SupplierName").val();
var selectedSearchType = $("#SelectedSearchType option:selected").val();
var supplierInvitationObject = $('#SupplierInvitation').serializeObject();
supplierInvitationObject.SupplierName = supplierName;
supplierInvitationObject.SelectedSearchType = selectedSearchType;
There appears to be an interop issue between Microsoft Edge and other browsers when you attempt to serialize from the fieldset. I've authored a short test to help track future support:
var serialized = $('<fieldset><input name="a" value="b"></fieldset>').serialize();
document.body.textContent = ( "a=b" == serialized ? "pass" : "fail" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have filed an issue for the Microsoft Edge team to investigate the matter further. I'll also be working through the internals of this method to more closely identify the point at which Edge deviates from expectations. I will update this answer when I have additional details.

How to get the value of an EditorFor JavaScript ASP

I want to get the value of an EditorFor in ASP but it returns me nothing.
Thank you for your helps
<div class="form-group" id="ParticipantNumber">
#Html.LabelFor(model => model.ParticipantNumber, new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.ParticipantNumber)
</div>
</div>
My JavaScript code
$('#ParticipantNumber').keyup(function () {
var s = $('#ParticipantNumber').val();
console.log(s)
}
Your JavaScript is looking for $('#ParticipantNumber'), which is the element with the ID ParticipantNumber. Your code defines the editor with:
#Html.EditorFor(model => model.ParticipantNumber, new {
#class = "ParticipantNumber", disabled = "disabled" })
The intention here is to assign the input with the class ParticipantNumber, which would have meant you could address it with `$('.ParticipantNumber') instead.
However, the parameter you're using is additionalViewData; the EditorFor HTML editor does not have a property to reflect HTML properties back into the renderer. Your two options are:
Write a custom template
Change the way you're referencing the input
Option 1 is possibly a bit over-the-top for your needs; with option 2, the following will solve your problem, by simply referencing the input within your <div id='ParticipantNumber'>:
#Html.EditorFor(model => model.ParticipantNumber)
$('#ParticipantNumber input').keyup(function () {
var s = $(this).val();
console.log(s)
}
I'm a bit late coming to this party but I recently had this issue with Html.EditorFor.
What fixed it for me was to simply switch to TextBoxFor. So instead of:
#Html.EditorFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled", id="ParticipantNumber" })
Change it to:
#Html.TextBoxFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled", id="ParticipantNumber" })
In the javascript, you are querying for the "id" attribute, but #Html.EditorFor does not emit any id by default. You can modify your code like this
#Html.EditorFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled", id="ParticipantNumber" })
Then your javascript will work.

Categories

Resources