Confirmation message in webgrid - javascript

I am using Webgrid in MVC.And I was added in default column in the webgrid with link button(anchor tag). Now I want when the button click shown a confirmation message . But I tried in below code
gridColumns.Add(grid.Column(
format:
#<text>
#if (item.complianceStatusId == (int)SchoolBreifcase.Models.Status.Tobeverified)
{
#Html.ActionLink("Complete", "CompleteComplianceTask", new { complianceId = item.ComplianceId, statusId = item.complianceStatusId },
new { onclick = "return confirm('Are you sure you wish to complete this compliance ?');" }, new { #class = "gridButton" })
}
</text>
Its showing error like : The best overloaded method match for 'System.Web.Helpers.WebGrid.Column(string, string, System.Func<dynamic,object>, string, bool)' has some invalid arguments
I removed the css class or confirmation ,then Its working fine .But I want to confirmation message ,and assign CSS class in the same field . How to do i solve this ??
I think i want for set css style like as webgrid,a {Styles } then we can remove the #class field in the anchor tag . But I try this .the css style not assigned in gridview button .
Edit:
Now i got the answer .I just changed for like below code
#Html.ActionLink("Complete", "CompleteComplianceTask", new { complianceId = item.ComplianceId, statusId = item.complianceStatusId },
**new { #class = "gridButton", onclick = "return confirm('Are you sure you wish to complete this task ?');"** })
I am assigned the css class and confirmation messge in same object ,then it working perfect .

Related

ASP.NET MVC 4 Having trouble selecting the correct input element using js/jquery

I'm working with a form that I've built using HTML helpers, like so:
#using (Html.BeginForm("CreateNewRoom", "Admin", FormMethod.Post, new { #enctype = "multipart/form-data", #class = "form-vertical", style = "margin-top:-30px" }))
{
<fieldset>
<legend>Create a new Room</legend>
<div class="form-toolbar sepa">
<label class="darkBlue toolbar-label">Room name:</label>
<div>
#Html.TextBoxFor(x => x.name, new { #id = "room", #class = "form-control-static", #style = "margin-bottom:5px;", #autofocus = "true" })
</div>
</div>
...
<div class="form-toolbar sepa">
<label class="darkBlue toolbar-label">Display:</label>
<div>
#Html.RadioButtonFor(x => x.display, "True") Yes&nbsp
#Html.RadioButtonFor(x => x.display, "False") No&nbsp
</div>
...
Just in case it helps, Chrome DevTools informs me that this is the HTML being displayed by my radio button helper:
<input id="display" name="display" type="radio" value="True">
" Yes "
<input checked="checked" id="display" name="display" type="radio" value="False">
" No "
I have a Javascript file which dynamically plays with the elements on the page. I would like for js to add a class to an element on the page, to simply change its opacity to 0.5, if it finds that the "No" radio button is selected.
if ($('input[name="display"]').val() === "False") {
if (($('#selectedRoomName')) && ($('#selectedRoomArrow')))
$('#selectedRoomName').addClass('obscured');
$('#selectedRoomArrow').addClass('obscured');
} else {
//sad
}
I've used this block in $(document).ready and in $(input[name="display"]).change, to make js add the class if display is 'False' when the page loads, and also to add it if the 'False' radio button is selected.
However, I found that js had a problem reading the value of the input, and thinks that it is true almost all the time, even if the false button is selected. I'm assuming it must be something to do with the fact that the two inputs have the same name?
My question is, how do I ensure that js always picks the input that is currently selected, and will this make sure that it reads the correct value?
UPDATE: I have changed $('input[name="display"] to $('input[name="display"][checked="checked"]'), in an effort to make js home in on whichever radio button is checked. This solves the problem where js did not know which button was checked on page load. However, now it always targets whichever button was checked on page load, instead of the button that's actually checked currently.
Apologies if I seem like a complete novice, but I am, so...
Any and all suggestions on how to better organise my code are welcome; I'm very unfamiliar with best practises in web dev.
Thanks!
Just change the following line in your change event from :
if ($('input[name="display"]').val() === "False") {
to:
if ($(this).val() === "False") {
This will check for the value of the radio button that is current clicked.
I used a combination of #Ehsan's answer, and a partial solution that I included in an update to the the question.
I decided to place the js block in a function, which took the element whose value I was checking as a parameter:
function checkdisplay(dispradio) {
var a = document.getElementById("selectedRoomName");
var b = document.getElementById("selectedRoomArrow");
if ((a) && (b)) {
if (dispradio.val() === "False") {
a.className += " obscured";
b.className += " obscured";
} else {
a.className = a.className.replace(/(?:^|\s)obscured(?!\S)/g, '');
b.className = b.className.replace(/(?:^|\s)obscured(?!\S)/g, '');
}
}
}
Then I called the function in two places like so:
//first for document load
$(document).ready(function () {
checkdisplay($('input[name="display"][checked="checked"]'));
});
and
//and then for change events
$('input[name="display"]').change(function () {
checkdisplay($(this));
});
Seems like [checked="checked"] was needed to let js know which button was checked on page load, but that then needed to be removed for onchange events, or js would target whichever button was checked on page load, rather than the button that was actually checked!
Many thanks for your partial solution #Ehsan, it helped me come up with this one!

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

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.

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

Closing an HTML form in a jQuery modal with the submit button

I have inherited the following HTML form in a jQuery modal:
<div id = "openModal" class = "modalDialog">
<div>
X
<form id = "write_us_form" action="" method = "post">
<div class = "form_container">
<label class = "form_label">Name</label>
<input type = "text" class = "form_textfield" name = "f_name"><br>
<label class = "form_label">E-mail</label>
<input type = "text" class = "form_textfield" name = "f_email"><br>
<label class = "form_label">Subject</label>
<input type = "text" class = "form_textfield" name = "f_subject"><br>
<label class = "form_label">Message</label>
<textarea class = "form_textarea" name = "f_message" rows = "5"></textarea>
<input type = "submit" class = "form_submit_button" value = "Send message">
</div>
</form>
</div>
</div>
When I click the submit button, the following jQuery script runs, apparently to not refresh the page and run the send_form.php file to send an email:
$(function ()
{
$('#write_us_form').on('submit', function (e)
{
e.preventDefault (); // prevent page reload
$.ajax (
{
type : 'POST', // hide URL
url : 'send_form.php', // form validation file
data : $('#write_us_form').serialize (),
success : function (data)
{
$('#openModal').dialog('close');
alert ('Thank you for contacting us!');
}
});
});
});
The code does not do two things:
1. Close the modal. I already added the dialog('close') part, but it does not have any effect.
2. If I close the modal with the close button, and then click the proper button on the website that displays the modal, the form still has the previous contents in it.
The php part works, the proper email is sent, I'm just trying to find a way to close the modal and possibly refresh the form when it is opened again.
Thanks for any bit of help!
Edit:
Your dialog box might not be closing if your ajax call is not successful. If your 'Thank you for contacting us' alert is being executed and your modal is still not closing, it could be an issue with your syntax. It could be the case, that your modal is a bootstrap modal in which case the syntax would be different. You would want to hide the modal.
In the case of the form contents, you want to reset the form in the success block. See your modified code below:
$('#write_us_form').on('submit', function (e)
{
e.preventDefault (); // prevent page reload
$.ajax (
{
type : 'POST', // hide URL
url : 'send_form.php', // form validation file
data : $('#write_us_form').serialize (),
success : function (data)
{
$('#openModal').modal('hide');
$("#write_us_form").trigger("reset");
alert ('Thank you for contacting us!');
}
});
});
});

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