Call Action From view - asp.net-mvc

This is my action :
[HttpPost]
public ActionResult AddDispo(string idv, string dd, string df)
{
try
{
Models.indisponible model = new Models.indisponible();
model.Dd = Convert.ToDateTime(dd);
model.Df = Convert.ToDateTime(df);
model.idv = idv;
entity.indisponible.AddObject(model);
entity.SaveChanges();
TempData["Resultat"] = "La nouvelle date a été ajouté courrectement";
return RedirectToAction("Dispo", "Agence", new { idv = idv});
}
catch (Exception)
{
TempData["Resultat"] = "Une erreur se produiset Vielliez ressaiyer";
return RedirectToAction("Dispo", "Agence", new { idv = idv});
}
}
I want to call this action without using Html.beginForm from my view, i have made this trial but it hasn't worked :
<%: Html.Action("Accepter", "Adddispo", new { id = Model.idv, dd = Model.Dd, df = Model.Df })%>

Your Action method is of type HTTPOST. So you need a form posting for that action to get invoked. If you do not wish to use the form tag in your view, you may use jQuery to do a POST.
The below example does a post when user clicks on a button woth ID btnPost.
HTML ( Content of Your View)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
Name : <input type="text" id="txtName" /> <br/>
Age: <input type="text" id="txtAge" /> <br/>
Place : <input type="text" id="txtPlace" /> <br/>
<input type="button" value="Save" id="btnPost" />
<script type="text/javascript">
$(function(){
$("#btnPost").click(function(e){
e.preventDefault(); // preventing the default button submit behaviour
var name=$("#txtName").val(); //reading the text box values
var age=$("#txtAge").val();
var place=$("#txtPlace").val();
$.post("YourController/AddDispo", { idv :name, dd : age, df=place} ,function(data) {
//Do whatever with the the response. may be an alert
alert(data);
});
});
});
</script>
What it does
1) In the head section of the document, we included the reference to the jQuery library. I am including a reference from the google CDN. You may change that to include your local copy. If you are working with ASP.NET MVC, the default project template has this under the Scripts folder(version number may be different).
2) In the document ready event ($(function(){..) we are binding some functionality to the button which has an ID btnPost. We are binding the functionality on the click event. So whenever user clicks on that button, that piece of code will be executed.
3) We are reading the text box values, and making use of the post method of jQuery. It will post the data we are passing ( we are passing the values of text boxes here) to the action method. once the action method returns something back to the calle, it will be stored in the data variable. you can do further things (show some message to user/ reload some content) after checking the value of that.

Action link will always send a "GET" request. Either remove that [HttpPost] attribute from your controller action, or use a similar technique suggested by shyju. Action link has some issues with windows events, so you should stick to stylized buttons unless there is specific need for anchors. A sample styling will be :
#mybutton input[type=submit] {
background: none;
padding: 0px;
font-family: arial;
font-size: 1em;
cursor: pointer; // to make it look like link
border: none; // --- " -----
}

Related

DirtyForms does not work properly with $.blockUI

I'm using DirtyForms and $.blockUI plugin, the latter to change pages when clicking on links (in my app, some pages take a couple of seconds more to load and a visual feedback is fine).
When I change field content and then click any link, DirtyForms is triggered: but when I cancel the process to stay on the page, $.blockUI starts its game, resulting in a stuck page
$('form[method="post"]').dirtyForms();
$('a').on('click', function(){
$.blockUI();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
<p>Change the field content to activate DirtyForms, then click on the link.<br>
When the popup appears, click on "cancel" to stay on the page.<br>
Watch blockUI getting fired as the link is going to be followed</p>
<form action="#" method="post">
<input type="text" name="username" required>
<button type="submit">send</button>
</form>
click me after changing field content
Please, any solution?
EDIT: I also tried with stay.dirtyforms and afterstay.dirtyforms events, but they have no effect. defer.dirtyforms seems to work but the event is triggered twice (I put a console.log() to check) and I am not sure this is the way to go...
I've edit my answer: I've added some line of code to disable first the onbeforeunload dialog alert, taken from here. And at the end a link to an answer with another idea you can try.
My idea: you have to prevent the default link action and use the $.blockUI Modal Dialogs methods to open a custom dialog, then catch the link attribute href from the link put it inside a variable and use the variable value for the #yes button of the dialog.
See if this solution can meet your needs
/* beforeunload bind and unbind taken from https://gist.github.com/woss/3c2296d9e67e9b91292d */
// call this to restore 'onbeforeunload'
var windowReloadBind = function(message) {
window.onbeforeunload = function(event) {
if (message.length === 0) {
message = '';
};
if (typeof event == 'undefined') {
event = window.event;
};
if (event) {
event.returnValue = message;
};
return message;
}
};
// call this to prevent 'onbeforeunload' dialog
var windowReloadUnBind = function() {
window.onbeforeunload = function() {
return null;
};
};
var linkToFollow; // href to follow
$('form[method="post"]').dirtyForms();
$('a').on('click', function(e){
e.preventDefault();
windowReloadUnBind(); // prevent dialog
$.blockUI({ message: $('#question'), css: { width: '275px' } });
linkToFollow = $(this).attr('href');
});
$('#no').click(function() {
$.unblockUI();
return false;
});
$('#yes').click(function() {
$(window.location).attr('href', linkToFollow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
<p>Change the field content to activate DirtyForms, then click on the link.<br>
When the popup appears, click on "cancel" to stay on the page.<br>
Watch blockUI getting fired as the link is going to be followed</p>
<form action="#" method="post">
<input type="text" name="username" required>
<button type="submit">send</button>
</form>
click me after changing field content
<div id="question" style="display:none; cursor: default">
<h6>Would you like to contine?.</h6>
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" />
</div>
Other idea taken from another answer: Other idea would be to make a simple jQuery.ajax({}) call before return value in beforeunload as seen in this answer

Ajax Single Field Submission in form

I've created an order form, of which has a large array of fields. I'm now adding coupon functionality so that we can start to give customers discount codes etc.
What's the best way of submitting a single field (the coupon code) using ajax after a "apply coupon" button has been clicked so that the price can be updated on the front end probably using UJS(?) - obviously the final price calculation would happen on the backend?
Cheers.
I would recommend using a JS framework to do Ajax requests. If you JQuery, then you can use the example given to understand how to do a simple post.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post and put the results in a div */
$.post( url, { s: term },
function( data ) {
var content = $( data ).find( '#content' );
$( "#result" ).empty().append( content );
}
);
});
</script>
</body>
</html>

ASP.NET MVC Required Field Indicator

For fields in my ASP.NET MVC view that have been attributed as required, is there any way for the framework to render some sort of indicator automatically that the field is marked as required in metadata?
Should be able to do this with CSS since MVC3 adds in those custom attributes to the element:
<input data-val="true" data-val-required="The Username field is required." id="Username" name="Username" type="text" value="" />
You could key off the data-val-required in CSS like so:
input[data-val-required] {
background:red
}
or set a background image of an asterisk etc.
I did that way because my required fields must be dynamic (defined in a configuration file)
Add at the end of your View:
<script type="text/javascript">
$('input[type=text]').each(function () {
var req = $(this).attr('data-val-required');
if (undefined != req) {
var label = $('label[for="' + $(this).attr('id') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red"> *</span>');
}
}
});
</script>
I modified Renato Saito's answer to include more field types (all types of input and select lists) and use the jQuery namespace instead of the generic $. Here is my revision:
<script type="text/javascript">
// add indicator to required fields
jQuery('input,select').each(function () {
var req = jQuery(this).attr('data-val-required');
if (undefined != req) {
var label = jQuery('label[for="' + jQuery(this).attr('id') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red"> *</span>');
}
}
});
</script>
Here is one that will attach a red asterisk to the right side of anything with the attribute 'data-val-required'.
<script type="text/javascript">
$('[data-val-required]').after('<span style="color:red; font-size: 20px; vertical-align: middle;"> *</span>');
</script>
Adding html attribute is not enough. This will only cause javascript validation error. If you want to indicate that the field is required you'd probaly want to add an asterisk to it. You can do it by means of extenssion method of HtmlHelper. You can find a thorough explanation here
Indicating required field in MVC application
A Small Modification Is Done From My Side.
Actually I had primary keys (Identity Columns in DB). That I did no want to highlight.
So I Used Below Code Snippet to select only input[type=text] fields that has required attribute in annotation.
$("[data-val-required]").not(":hidden").not(":radio").not(":checkbox").after('<span style="color:red;max-width:10px;min-height:30px;">*</span>');

loading gif in mvc

I have a method in my controller like this
public string UpdateResource()
{
Thread.Sleep(2000);
return string.Format("Current time is {0}", DateTime.Now.ToShortTimeString());
}
I have a html button in my view page and when I click on that I want a loading gif image to appear and then disappear after 2000ms. Below is my html
<input type="button" id="btnUpdate" value="Update" />
<img id="loading" src="/Images/ajax-loader.gif" alt="Updating ..." />
<div id="result"></div>
How can I call the controller method. I have seen Html.ActionLink but I want this on button click and not a hyperlink.
Please help
First change to UpdateResource method. Now it returns ActionResult:
public ActionResult UpdateResource()
{
Thread.Sleep(5000);
return Content(string.Format("Current time is {0}", DateTime.Now.ToShortTimeString()));
}
We have to hide image when document is loaded so we change image tag to:
<img id="loading" src="../../Content/progress.gif" alt="Updating ..." style="display: none;" />
We have added style="display:none".
Then we are using jQuery:
<script type="text/javascript">
$(document).ready(
function() {
$('#btnUpdate').click(
function() {
$('#loading').show();
$.get('<%= Url.Action("UpdateResource") %>', {},
function(data) {
$('#result').html(data);
$('#loading').hide();
});
}
);
}
);
</script>
When document is loaded, we are setting click action to your button. It shows progress and then uses ajax to get ActionResult. When ActionResult comes back, we are hiding progress and setting content of #result div with returned data.

Problem binding action parameters using FCKeditor, AJAX and ASP.NET MVC

I have a simple ASP.Net MVC View which contains an FCKeditor text box (created using FCKeditor's Javascript ReplaceTextArea() function). These are included within an Ajax.BeginForm helper:
<% using (Ajax.BeginForm("AddText", "Letters",
new AjaxOptions() { UpdateTargetId = "addTextResult" }))
{%>
<div>
<input type="submit" value="Save" />
</div>
<div>
<%=Html.TextArea("testBox", "Content", new { #name = "testBox" })%>
<script type=""text/javascript"">
window.onload = function()
{
var oFCKeditor = new FCKeditor('testBox') ;
var sBasePath = '<%= Url.Content("~/Content/FCKeditor/") %>';
oFCKeditor.BasePath = sBasePath;
oFCKeditor.ToolbarSet = "Basic";
oFCKeditor.Height = 400;
oFCKeditor.ReplaceTextarea() ;
}
</script>
<div id="addTextResult">
</div>
<%} %>
The controller action hanlding this is:
[ValidateInput(false)]
public ActionResult AddText(string testBox)
{
return Content(testBox);
}
Upon initial submission of the Ajax Form the testBox string in the AddText action is always "Content", whatever the contents of the FCKeditor have been changed to. If the Ajax form is submitted again a second time (without further changes) the testBox paramater correctly contains the actual contents of the FCKeditor.
If I use a Html.TextArea without replacing with FCKeditor it works correctly, and if I use a standard Post form submit inplace of AJAX all works as expected.
Am I doing something wrong?
If not is there a suitable/straight-forward workaround for this problem?
The problem is unrelated to MVC but caused by using FCKeditor in conjunction with AJAX. To fix in the code above I added the following to the submit button's onclick event:
<input type="submit" value="Save" onclick="FCKeditorAPI.GetInstance('TestBox').UpdateLinkedField();" />
For more information see here.

Resources