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;
})
})
Related
I have a problem where I need to call jQuery code to fetch a value from an HTML element like following:
#using (Html.BeginForm("Login", "Home",new { Checked = $('#checkbox5').checked }, FormMethod.Post,new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
}
Note that besides passing the entire model into my Login action I'm trying to pass an optional parameter named "Checked". This parameter basically states whether the "remember me" checkbox has been checked on the form or not.
The checkbox itself is not the one that .NET uses by default like:
#Html.CheckboxFor(somepropertyhere);
But instead a regular checkbox like this:
<input id="checkbox5" type="checkbox">
<label for="checkbox5">
Remember me?
</label>
How can I fetch this checkbox's value when passing it as an extra parameter besides my model?
So that my method in the end would look like:
Public ActionResult Login(bool Checked, LoginViewModel model)
{
// To have the checked value here now...
}
P.S. And I can't use Html.CheckboxFor for some reasons, but I don't wanna get too much into details since the question wouldn't make sense then (maybe it doensn't even now I'm not sure if this is doable what I'm trying to achieve).
Can someone help me out?
You can get checkbox value in Controller using Checkbox Field name like this :
bool isRememberMe=Request.Form["CheckBoxName"];
if you want to send any variable, you should set name for field, and on serverside you can call it with name
<input id="checkbox5" type="checkbox" **name="checkbox_name"** value="true">
<label for="checkbox5">
Remember me?
</label>
on server side
Public ActionResult Login(bool checkbox_name = false, LoginViewModel model){
// To have the checked value here now...
}
You can't use JavaScript within a Razor block, because they run at entirely different times. The Razor code runs server-side, long before the response is ever sent to the client. JavaScript runs client-side, only after the server has sent its response to the client, and Razor has already done its work.
On first load, the value of your checkbox will always be the default, which in your case is false. That's why none of the other answers help you. The user would have to interact with the checkbox and submit the form first, and then the checkbox would have that user-set value within the post action that handles the form. If you returned to the form, because of an error, then you could utilize the checkbox value.
To actually alter the form action without posting first, you'd have to handle the click event of the checkbox and manually change it via JavaScript. However, that's extremely brittle. If you want the value of the checkbox on post, then just bind it to something your action accepts. For example:
#Html.CheckBox("checked", Request["checked"] as bool? ?? false)
Then:
[HttpPost]
public ActionResult MyPostAction(MyClass model, bool checked)
I really don't understand why you don't want to use a new property model for the RememberMe value, but I think this might work for you:
Assuming your View looks like this:
#using (Html.BeginForm("Login", "Home", FormMethod.Post, new { #class = "form-horizontal", role = "form", id = "login-form" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(x => x.Username, new { #class = "form-control" })
#Html.TextBoxFor(x => x.Username, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(x => x.Password, new { #class = "form-control" })
#Html.PasswordFor(x => x.Password, new { #class = "form-control" })
</div>
<div class="form-group">
<input id="checkbox5" type="checkbox">
<label for="checkbox5">Remember me?</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
</div>
}
And assuming your Controller looks like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, bool rememberMe)
{
// Do something with 'rememberMe'
// Do something with 'model'
return RedirectToAction("Index");
}
Then you must need a Javascript like this in your login view to replace the form action before the submit event was completed:
$(function () {
var form = $("#login-form");
var checkbox5 = $("#checkbox5");
form.submit(function () {
var checked = checkbox5.is(":checked") ? "true" : "false";
var action = updateQueryStringParameter(form.action || '', "rememberme", checked);
form.attr('action', action);
});
// stolen from http://stackoverflow.com/a/6021027/1605778
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
});
Let me know if this works for you.
Just to give more context: when you have a parameter of a primitive type (like bool or int) in your action, MVC expects this parameter in the Url; but the values of the Complex Types (like LoginViewModel) should pass as a Request Body in the HTTP POST. So if you want to pass both (complex and primitive) you need to be careful to pass all primitive types in the url and the values of complex types in the request body.
The POST of the Login Form could looks like:
POST /Home/Login?rememberMe=false
username=admin&password=secret
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.
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());
};
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.
On the client side I need to call javascript function "changeSchool" with selector's Id as parameter, as soon user selects new option (school in this case). How to pass selector's Id to such javascript function?
Table in the view contains following drop down lists:
#{
for (var i = 0; i < Model.StudentApplications.Count(); i++)
{
<tr>
...
<td>#Html.DropDownListFor(m => m.StudentApplications[i].SchoolId, Model.StudentApplications[i].SchoolList, new { onchange = "changeSchool(?);" })</td>
...
</tr>
}
}
EDIT:
From the source code I can see that ids is generated: id="StudentApplications_0__SchoolId",
id="StudentApplications_1__SchoolId", ...
etc.
Perhaps?
onchange = "changeSchool(" + Model.StudentApplications[i].SchoolId + ");"