ASP.NET MVC Fill a label at the click of a button - asp.net-mvc

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

Related

Populating a ViewModel with the current form data before sending it off via JSON

I'm creating an ASP.NET MVC 5 SQL Server (Entity Framework, database-first) application where there is an order record and a set of line item records attached to it. I am using viewmodels to display the data. The user can add new line item records to the viewmodel through an "Add" button, but the line items are not committed to the database until the user clicks the "Save" button. (I've previously written about the application regarding a different issue: ASP.NET MVC - passing modified viewmodel from AJAX to view)
I have the "Add" button working fine... except for one very important use case. If the user changes some data in the web page then presses the "Add" button, none of the changes to the web page data are sent when the #Html.Raw(Json.Encode(Model)) line is called:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#mybutton").click(function () {
$.ajax({
url: "../AddNewLineItem/",
cache: false,
type: "POST",
data: {
'viewModel': #Html.Raw(Json.Encode(Model)),
},
success: function (data) {
$('#divPartial').append(data);
},
error: function (reponse) {
alert("Error: " + reponse);
}
});
});
});
</script>
Obviously, the reason why this is happening is because the model has not been updated with the latest data from the web page. However, how do I force the model to be updated before shipping it off via JSON? (Alternately, is there some way to always keep the viewmodel in sync with what the user has typed in the form?)
the Model object is a server-side entity that doesn't exist on the client. instead, you need to send the client data. try using jQuery's serialize method. this will take all elements in the form and turn it into an object that can be sent via the AJAX method:
data: {
'viewModel': $("form").serialize(),
},

How to autosubmit form before an actionlink invokes?

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

How to receive Open/Save file dialog after ajax-form post with ASP.NET MVC and jQuery

I want to be able to receive open/save dialog for a pdf file being returned from controller without using 'Html.Beginform' in ASP.NET MVC. I´m using 'Ajax.Beginform' since I can register events to fire OnBegin and OnComplete (which I think I can´t do when using Html.Beginform, or is it?).
I want to state that the problem is not creating and receiving the file from the server when using 'Html.Beginform' because that works fine, but without the events I want to use. I´m using 'Ajax.Beginform' and the file is being returned from the controller but nothing happens after that client side.
My cshtml
#using (Ajax.BeginForm("CreatePdf", "Print", null, new AjaxOptions() { LoadingElementId = "printLoading", OnSuccess = "printPageComplete"}, new { id = "exportForm" }))
{
//Stuff abbreviated
<input type="button" onclick="onPrint()" />
}
My jQuery
function onPrint()
{
//Stuff abbreviated
$("#exportForm").submit();
}
function printPageComplete(result)
{
//this 'result' variable is obviously holding the file from the controller
//stuff abbreviated
//TODO: I need to open file dialog here
}
My Controller
[HttpPost]
public ActionResult CreatePdf(FormCollection collection)
{
//Stuff abbreviated
return File(thePdf, _mimeTypes[ExportFormat.Pdf], "thePdf.pdf")
}
As you can see I´ve managed to get this far as in the printPageComplete function but I´m not sure where to go from here. Should I continue using the ajax form or should I stick with the html form and try to find other way to fire the events I so sorely need to use?
Perhaps I´m going about this all wrong and your help would be very well appreciated.
You can post a form without using Ajax.BeginForm. It is more work, but gives you more flexibility:
$('#exportForm').submit(function (e){
e.preventDefault();
//Do any validation or anything custom
$.ajax({
//set ajax settings
success: function(){
// Handle the success event
}
});
});

Long action and waiting for a new view in ASP.NET MVC 3

I'm using ASP.NET MVC3. In the view, I have a link in view that initiates a new request:
#Html.ActionLink ("Link", "LongAction", "Home")
The action "LongAction" takes a long time, and while waiting for the new view I want show an image that simulates loading a whole new view:
public ActionResult LongAction()
{
Threas.Sleep(10000);
return View();
}
You can do something like this:
User Clicks button
Show a loading GIF
POST/GET to a server endpoint
Server endpoint kicks of the long running task.
On the complete event of the ajax request hide the loader.
Notify user
You can look into binding it together with Jquery, or if you want to use something in the mvc framework you can look at the Ajax ActionLink. Either way you can hide/show the loader with javascript.
JQuery Example:
$('#userButton').click(function(){
longRunningTask();
return false;
});
function longRunningTask()
{
$('#loader').show();
$.ajax({
url: 'http://serverendpointaddress.co.uk'
}).done(function(){
//notify the user
}).always(function() {
$('#loader').hide();
});
}

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