Modify the text inside an Html.EditorFor MVC with jquery? - javascript

I'm working on a web application in which I have an EditorFor field for a date as follows:
#Html.EditorFor(model => model.FECHA_RETIRO, new { htmlAttributes = new { #class = "form-control datepicker" } })
I have a jquery method that selects an element from a dropdown list and depending on the selection has to retrieve its date from the database. The method is:
$("#SIGLA_CURSO").change(function () {
var selectedValue = $("#SIGLA_CURSO").val();
$.post('#Url.Action("obtenerFechasCurso", "PRESTAMOes")', { idCurso: selectedValue }, function (listaDatos) {
alert(listaDatos);
// handle the server response here
$("#FECHA_RETIRO").val(listaDatos[0]);
$("#Fecha_Fin_Prestamo").val(listaDatos[1]);
});
});
The thing is I want the FECHA_RETIRO field to show the date that I retrieve from the database, however I can't get to modify it. If I try to show a date in a textbox it works, but it doesn't using the editorfor and I think that that is the field I need to modify.
Is it possible using jquery? Thank you.

Related

Add Selected value from Combo Box to session and retrieve

In my asp.net web application, I load some data to the combo box in the Nav bar.
I want to do when someone selects the value from the combo box need to set this value to the session.
Then again when reloads the page needs to check that session value and if it is not null, set the combo box value to the session value.
So far my code, when the combo box change event it adds the value to the session.
But again loading the page the method that checks whether the session value is null or not returns an error.
I checked the inspect element, their session value is set from the script. But checking that value returns error
On the Layout page, I wrote like
#{
List<SelectListItem> MyBranch = Session["MyBranch"] as List<SelectListItem>;
if (Session["SelectedBranch"].ToString() != null) // Error is : System.NullReferenceException: 'Object reference not set to an instance of an object.'
{
string currentbranch = Session["SelectedBranch"].ToString();
MyBranch.Where(x => x.Value == currentbranch).First().Selected = true;
}
}
This is the combo box
<div class="dropdown">
#Html.DropDownList("MyBranch", MyBranch, new { #class = "form-control js-dropdown js-MyBranch", #Id = "Branch" })
</div>
This is getting the combo box change value and setting it to the session
$(function () {
$('.js-MyBranch').change(function () {
var bId = document.getElementById('Branch').value;
sessionStorage.setItem("SelectedBranch", d);
});
});

Why isn't my TextBoxFor displaying currency values correctly?

I have the following TextBoxFor on an MVC form:
<div class="col-xs-3">
#Html.TextBoxFor(m => m.SalesSubTotal, null, new { #class = "form-control", title = "", #tabindex = "-1", #readonly = "readonly", #style = "text-align:right", Value = String.Format("{0:C2}", Model.SalesSubTotal) })
</div>
The user will never actually enter a value in this field. The field is always updated via a line in a JavaScript function that looks as follows:
$("#SalesSubTotal").val(salesSubTotal.toFixed(2));
When the page first displays the input displays $0.00 as I would expect. However, when the field is updated, the currency symbol is never displayed. So, instead of displaying something like $90.15, it displays 90.15.
Can someone see what I'm doing wrong?
Your number format {0:C2} isn't active anymore when javascript is invoked:
$("#SalesSubTotal").val(salesSubTotal.toFixed(2));
will actually just set the field to the value with two decimals just like you have experienced it. You have to add the dollar sign there aswell to get the correct result:
$("#SalesSubTotal").val("$" + salesSubTotal.toFixed(2));
The string format is being applied when the element is rendered for the first time with Value = String.Format("{0:C2}", Model.SalesSubTotal), but then you change the value without that format in JS.
You can create a helper function that formats the value and use it like so:
(function() {
function currencyFormat(val) {
return `$${val.toFixed(2)}`;
}
let salesSubTotal = 90.1525346252;
$("#SalesSubTotal").val(currencyFormat(salesSubTotal));
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="SalesSubTotal">
Alternatively, you can extend the jQuery prototype with jQuery.fn.extend().
(function() {
$.fn.extend({
currencyVal: function(val) {
this.val(`$${val.toFixed(2)}`);
}
});
let salesSubTotal = 90.1525346252;
$("#SalesSubTotal").currencyVal(salesSubTotal);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="SalesSubTotal">

Url.Action call Javascript Function

I have an Url Action Link that sends to my controller 1 paramater, but I need that paramater to call a javascript function to get document.getElementById and send that value to my controller. In my view I have the follwoing code:
#foreach (var item in ViewBag.PersonsContacts as List<Software___FPPD.Models.Contact>)
{
<tr>
<td>#Html.DisplayFor(model => item.ContactType.Name)</td>
<td>#Html.EditorFor(model => item.ContactValue, new { htmlAttributes = new { #class = "form-control", id = "contactValue"} })</td>
<td>
Alterar
</td>
</tr>
}
My javascript:
function getValue(contactValue) {
document.getElementById("contactValue").value = contactValue;
}
What I'm I doing wrong because I can not get this to work.
Url.Action is a method which gets executed in the server by razor and your javascript executes on the client side. So it is not that easy to mix both.
I am not sure what you are trying to do. In your question you mentioned you want to set value to some form field. But since you are going to be redirected to the new page, there is no point ! whatever value you set is gone (unless you are opening the new page in a new tab)
Anyway, What you can do is to listen for the click event of the anchor tag in your javascript and do whatever you want at the client side (ex: setting some form field value /executing a javascript function etc).
You have some problem in your view code, you are creating the same id value for each item in the loop in #Html.EditorFor(model => item.ContactValue .Duplicate id's are not valid. So avoid that.
<td>
#Html.EditorFor(model => item.ContactValue,
new { htmlAttributes = new { #class = "form-control myContactVal"} })
</td>
<td>
<a href="#Url.Action("SignUp", "Home")" data-contactvalue="#item.ContactValue"
class="btn btn-success myEdit"> Alterar</a>
</td>
I added 2 new css classes , myContactVal and myEdit to the form fields to help us do our jQuery selection. We are setting the item.ContactValue value in html5 data attribute to the anchor tag for accessing later in our javascript code.
And the javascript to handle the link click event
$(function () {
$("a.myEdit").click(function (e) {
e.preventDefault();
_this = $(this);
var contactVal = _this.data("contactvalue");
var url = _this.attr("href");
url = url + "?contactValue=" + contactVal;
alert(url);
//You can do any other thing here.
//If you want to update the field with myContactVal class in prev td
_this.closest("tr").find(".myContactVal").val(contactVal);
// finally do the redirect
window.location.href=url;
})
})

Assign text from select list to a Hiddenfor field using Jquery

I'm trying to assign the text (not the value) from a MVC Html.DropDownListFor field to a HiddenFor field.
Right now I have the following code:
#Html.Label("Departure Route:", new { #class = "label-travel" })
#Html.DropDownListFor(m => m.DepartureRoute, routesSelectList, new { #class = "dropdown", #id = "Outbound-route" })
#Html.HiddenFor(m => m.DepartureRouteName, new {#id = "Outbound-route-name"})
I have tried to use Javascript / Jquery to take the selected field text in the dropdownlist and assign the text value to the model field (Hiddenfor)
What I have tried so far:
var InitializeRouteNames = function () {
$("DepartureRouteName").html = $("#Outbound-route option:selected").
};
Hope someone can see what I have done wrong.
Stephan showed me how to do this in the right way. I forgot to use the val() method in order to assign the HiddenFor value.
var InitializeRouteNames = function () {
$("#Outbound-route-name").val($("#Outbound-route option:selected").text());
$("#Return-route-name").val($("#Return-route option:selected").text());
};

How to pass value from jQuery script into ActionLink in MVC razor view

Hi all quick question i hope.
I want to pass a value from a jQuery script into HTML.ActionLink to details action in controller
It working like i choose item in dropdownlist and in jQuery i get an id of that item after it i want to get that id be passed into ActionLink how can i achieve it or what i supose to change in my code.
<script>
$(function() {
$('#reductions').change(function () {
var Id = $('#reductions').val();
});
});
</script>
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
#Html.DropDownList("reductions", new SelectList(dbContext.Reductions,"ReductionId", "Name")
</div>
</div>
</div>
#Html.ActionLink("Details", "Details", "Reductions", new {id = ????WHAT PUT HERE?????}, new {})
Please tell me what should i change in script area or in Action Link that i could make i work.
I already study a lot of examples but no one seems to be working for me
Instead of using the ActionLink Method create a normal HTML link and overwrite the href attribute with jquery.
<script>
$(function() {
var link = '#Url.Action("Details", "Details", "Reductions", new { id = "_myid_" })';
$('#reductions').change(function () {
var id = $('#reductions').val();
$('#myLink').attr('href', link.replace('_myid_', id);
});
});
</script>
... Your other html
<a id="myLink" href="">Details</a>
Instead of using plain HTML forms use this:
#using(HTML.BeginForm("Details","Reductions"))
{
//Your current HTML
}
You should also be using the #HTML.DropDownListFor() helper like this:
#Html.DropDownListFor("reductions", new SelectList(DBContext.Reductions, "ReductionId", "Name"), new { #class = "anyCSSClass" })
Replace your current #HTML.DropDownList() helper with this one.
To finish you must submit the form data to the server like this:
button type="submit" class="CSSClass" id="generatedContent"> Generate </button>
Heres the final code:
#using(HTML.BeginForm("Details","Reductions"))
{
#Html.DropDownListFor("reductions", new SelectList(DBContext.Reductions, "ReductionId", "Name"), new { #class = "anyCSSClass" })
button type="submit" class="CSSClass" id="generatedContent"> Generate </button>
}
You can accomplish this using JQuery/AJAX but its a lot more hassle than its worth as it goes against fundamental concepts of MVC and keeping server side logic separate from client side logic.
P.S. Check out the overloaded methods for both helpers here in the event that I mixed up the names of your controller/action methods.

Categories

Resources