How to autosubmit form before an actionlink invokes? - asp.net-mvc

I have an ActionLink:
#Html.ActionLink("Edit","Edit","Item",new{Id=ItemId),null}
There is a form at the top of the page which I need to save when the user clicks on this link and before the "Edit" action invokes.
So something to achieve this when the user clicks on the link may look like:
Save MasterForm
Carry on through to "Edit" Action on "Item" controller with "Id" parameter.
My instinct tells me that I may be looking for some JS??? Not sure.
Any help hugely appreciated.

The way to do this would be:
Add a click listener to the action link
Submit the form using Ajax
Follow the link manually by setting window.location
It would probably be a good idea to display some kind of spinner or popup while the form is submitting, so that the user knows something is happening.
For step 1, you need to select the <a> tags, so I suggest adding a class:
#Html.ActionLink("Edit","Edit","Item",new{Id=ItemId),new{#class="edit-link"}}
Then add some Javascript to intercept the click:
$(document).on("click", ".edit-link", function(e) {
// stop the browser from following the link
e.preventDefault();
var linkUrl = $(this).attr("href");
// submit the form via an Ajax post (assuming the form has "id=MasterForm")
var form = $("#MasterForm");
$.post(form.attr("action"), form.serialize(), function() {
// when complete, navigate to the original link
window.location = linkUrl;
});
});

Try this
#Html.ActionLink("Edit","Edit","Item",new{Id=ItemId),new {#id='btn-link'}}
In JS
$(document).ready(function(){
$('#btn-link').click(function(e){
saveMasterFormDetails();
});
});
function saveMasterFormDetails(){
var masterForm=$('#masterForm');
$.post(url,masterForm.serialize(), function(data){
});
}

Related

ASP.NET MVC Fill a label at the click of a button

I'm working on an email sending application. I have created a method to receive all emails. My goal now is to create a button of the genre (Select all) and the label for the recipient appear there all the emails contained in the database when I click on the button. My problem is that I do not know where to start nor do I have any examples
Method
[HttpPost]
public JsonResult GetEmails ()
{
ProjectEntities entities = new ProjectEntities ();
var emails = from User in entities.Use
             select User.Email;
return Json(emails);
}
Hi Dário, welcome to stack.
From your question i assume you are working on a Asp.net mvc application where you want to show a button in your view page(Html page) and when this button will be clicked then you will retrieve some data from database(as you already wrote a method for that).
To achieve that first you have to create a button in view. you can write some html code like below
<div id="label_id">
//comment: In this div email address will be shown after getting it from
//server.
</div>
<input type="button" id="btn_submit" value="submit"/>
Now you have to write a click event which will fire when someone click the submit button. It will send a post request using Ajax to server and get back your email address. please check jquery code, do not forget to add jquery link to your view file.
$(document).on('click','#btn_submit', function(){
$.ajax({
type: 'POST',
url: 'Controller/GetEmails',
dataType: 'json',
success: function (data) {
//comment you will find email address from this data object.
//bind data to view.
$('#label_id').html(data);
}
});
});
you can check this
article for better understanding of Asp.net mvc and Ajax

Get ID from modal window

I have a block of code running 3 times that will display some books and have a button to add a review.
Review button fires a modal popup with form to fill to create a review.
I am feeling dumb but I cant find a way to get a ID of a bookto use to create a review.
Was thinkink to display it within add reiew button params but dont know how to pass it after form submit (with other button pressed withtin form itself)
Template view for each book
<div class="book-#{book.id}">
... other stuff
<button class="review-create"> Write Review </button>
</div>
Javascript to display modal
$('.review-create').click(function(e) {
e.preventDefault();
// might not be parent() here but you can call parent() as many times as you want
var bookId = $(e.currentTarget).parent().attr('class').split('-')[1];
// other stuff for ajax or pass bookId into modal method
// Modal.displayForBook(bookId);
});
Now that your modal has the bookId, you can submit it through ajax by just referencing the variable. Hope this helps.
EDIT:
Because you can't edit the current script, you can write a new script in the view.
_book.html.erb
<script type='javascript/text'>
$('modal-button').click(function(e) {
$('review-create').attr('id', "#{book.id}");
});
</script
modal.html.erb
Your modal will submit ajax, dont make it do the form_for helpers
<script type='javascript/text'>
$('form.create').on('submit', function(e) {
var bookId = $(e.currentTarget).parent().attr('id');
// ajax call here
// on success, $(e.currentTarget).parent().attr('id', null)
});
</script>

Zend Framework 2 & jquery modal dialog

How does one go about displaying a controller action inside of jquery modal dialog?
Firstly you'll need your Javascript to load a url via ajax, this will depend on which kind of modal you are using etc, there's a ton of libraries out there. I will assume you are using the basic JQuery UI dialog Modal.
Example Link
<!-- this points to your action below.. -->
<a class="some-link" title="title here" href="mycontroller/test">testing</a>
Example Javascript (quick example found on google, many examples out there..)
$(document).ready(function() {
$('.some-link').each(function() {
var $link = $(this);
var $dialog = $('<div></div>')
.load($link.attr('href'))
.dialog({
autoOpen: false,
title: $link.attr('title'),
});
});
});
Now you need to make sure your action doesn't render the main layout when providing the content for the modal via the ajax request.
Here's a really simple method of doing that by replacing the base layout with an empty view for ajax requests. This isn't the best method but it's the simplest for this case ;)
Example Action
public function testAction()
{
if($this->getRequest()->isXmlHttpRequest()) {
$this->layout('application/layout/ajax-layout');
}
return new ViewModel(array()); // ..
}
application/layout/ajax-layout.phtml
<?php echo $this->content ?>
I think you want this kind of code http://jqueryui.com/dialog/#modal-message
inside the just display your action
Otherwise it's about to open an url into your modal it's like that http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/

jquery mobile page refresh

I want to refresh a page without using data-ajax="false" in anchor tag and i want to show the loading spinner while linking the pages in jquerymobile.pls help me.
reloadPage (boolean, default: false)
Forces a reload of a page, even if it is already in the DOM of the
page container. Used only when the 'to' argument of changePage() is a
URL.
Source: http://jquerymobile.com/demos/1.1.0-rc.1/docs/api/methods.html
So basically you can use $.mobile.changePage() to change pages and you can pass it the preloadPage : true option when you want to reload a URL.
Here is a quick example of how to use $.mobile.changePage() for links that have the reload class:
$(document).delegate('a.reload', 'click', function () {
$.mobile.changePage('myPage.html', { reloadPage : true });
return false;
});
The default loader in jquery mobile appears while linking to pages, by adding the following code:
$("a").click(function() {
$.mobile.showPageLoadingMsg();
//Other things you want to do
});

ASP.NET MVC multiple forms, staying on same page

I have forms located in multiple areas in my layout page (not nested).
I have a partial view which performs a post to controller action.
What action result do I return in that post to keep the user on the current page?
Is jquery/ajax my only option? I would rather a solution that didn't depend on javascript, maybe even a solution that degrades nicely.
You can use the Request.Referrer property to see what page the user has come from and then just use that to redirect them back there.
This does introduce other issues, e.g. losing ModelState, so you'll have to design for that. Also note that some users can block sending referrer information in their requests to the server - so the Referrer property can be null.
I would recommend using AJAX and then falling back on this.
You just need to do a RedirectToAction("") back to your main view.
To post a form without submitting the whole page, which refreshes the browser, you need to use Ajax/jQuery. The degraded solution is to submit the whole page like you would with a normal form.
Here's how I do it with jQuery.
Html:
<div id="RequestButtonDiv">
<button id="RequestButton" name="Request" type="button">Request</button>
</div>
This calls AddToCart on my Request controller when the RequestButton button is clicked. The response is placed inside the RequestButtonDiv element.
<script type="text/javascript">
$(document).ready(function () {
$('#RequestButton').click(function (event) {
$('#RequestButton').text('Processing...');
$('#RequestButton').attr('disabled', true);
submitRequest();
});
});
function submitRequest() {
$.ajax({
url: '<%: Url.Action("AddToCart", "Request", new { id = Model.RowId, randomId = new Random().Next(1, 999999) } ) %>',
success: function (response) {
// update status element
$('#RequestButtonDiv').html(response);
}
});
}
</script>
Controller action:
public ActionResult AddToCart(int id)
{
var user = AccountController.GetUserFromSession();
user.RequestCart.AddAsset(id);
return View("~/Views/Assets/Details_AddToCart.ascx");
}
The controller returns a partial view. You could also return Content("some stuff") instead.
Holler if you have questions or need more detail.

Resources