How to get the value of an EditorFor JavaScript ASP - javascript

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.

Related

Combo Box selected value to javascript

In my ASP.NET MVC web application, I send some data to the combo box using the view bag from the controller to the view.
In the view, there is a javascript when the combo box value is changed, I send that value to the controller again using an ajax call and get the related data, and show it in another textbox.
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName");
View
<div class="form-group row">
#Html.LabelFor(model => model.Task_Assigned_Branch_Id, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownList("Task_Assigned_Branch_Id", null, "Select the Branch", new { #class = "form-control js-dropdown js-Branch", #Id = "Branch" })
#Html.ValidationMessageFor(model => model.Task_Assigned_Branch_Id, "", new { #class = "text-danger" })
</div>
</div>
Javascript
$('.js-Branch').change(function () {
GetBranchMembers($(this).val())
});
This worked perfectly.
Then I want to change it, when sending the data to the view bag, I wanted to select a default value to the combo box and send it to the view.
So I changed the controller code to
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName", branchId);
Now the value is loading as the default selected value in the combo box.
So to get the combo box value in the loading event I wrote this
$(document).ready(function ()
{
var e = document.getElementById("js-Branch");
alert(e);
GetBranchMembers(e)
})
But the id returns null.
I guess because I sent the default value to the combo box, it doesn't pass the id to the script or something. Is there any other way of doing this?
Try using below code. i think you are using wrong id. you are using a class name in getElementbyId function
$(document).ready(function ()
{
var e = document.getElementById("Branch");
alert(e);
GetBranchMembers(e)
});

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

CKEditor showing HTML tags in ASP.MVC with decode

Everything works perfectly with create/edit pages, where CKEditor encodes input and server side returns decoded for CKEditor to display.
All that goes out of the window when validation error occurs making page reload after it hit the server.
Even though I am decoding on return to the view, CKEditor won't properly render html tags.
If I do Html.Raw for the same field, I can see its showing html properly, so its no the issue with decoding. For the life of me I can't figure out why this case is any different from editing ( loading existing html into CKEditor from dB) which works perfectly. But on page reload it all goes out of whack.
Things I've tried, decoding, encoding, neither. Adding delay to CKEditor initialization.
Server side return code.
if (!ModelState.IsValid)
{
q..Text = System.Net.WebUtility.HtmlDecode(q.Text);
return View(q);
}
View
<div class="form-group">
#Html.LabelFor(model => model.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Question.Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Raw(Model.Text)
</div>
</div>
JavaScript for CKEditor
var ckEditorInstance;
$(document).ready(function () {
CKEDITOR.replace('Text', { htmlEncodeOutput: true, enterMode: CKEDITOR.ENTER_BR });
ckEditorInstance = CKEDITOR.instances.Text;
ckEditorInstance.on('instanceReady', function () { UpdateTextArea(); });
ckEditorInstance.on('change', function () { UpdateTextArea(); });
});
function UpdateTextArea() {
ckEditorInstance.updateElement();
};
</script>
Using CKEditor v4.8.0 • 13-12-2017
Image to show the issue, below CKEditor #Html.Raw(Model.Text) output, showing that html is decoded properly.
Resolved this by using #Html.Raw(Model.Text) Instead of TextAreaFor
With #Html.HiddenFor(model=>Model.Text)
To preserve data when posting to server/controller
And Javascript to update hidden field and encode html
<script type="text/javascript">
var ckEditorInstance;
$(document).ready(function () {
CKEDITOR.replace('ckEditorRaw', { enterMode: CKEDITOR.ENTER_BR });
ckEditorInstance = CKEDITOR.instances.ckEditorRaw;
ckEditorInstance.on('instanceReady', function () { UpdateTextArea(); });
ckEditorInstance.on('change', function () { UpdateTextArea(); });
});
function UpdateTextArea() {
ckEditorInstance.updateElement();
//Set hidden field and escape html
$("#Question_Text").val(new Option((ckEditorInstance.getData())).innerHTML)
};
</script>

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

Thousands separator with razor MVC and js

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: ...

Categories

Resources