I am going following steps:
in the controller action no.1 redirect to view no1;
in view no.1 I want to display cshtml page and next I want to redirect to the new action no.2 by using
#{Response.Redirect(Url.Action("CreatePdf", "Home");}
directive;
Action no.2 is reached and I've got my result (pdf file) but I can;t see the view no.1 from which I've called this action.
How can I load this view and display html page?
Just a little tweak to #DavidG's answer:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(DownloadPdf, 1000);
});
function DownloadPdf() {
location.href = "#Url.Action("CreatePdf", "Home")";
}
</script>
Just tested and working. It will download the file after 1sec
A redirect causes the entire session to be directed to the new page ans loses anything you have sent out. I would use jQuery instead:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(DownloadPdf, 1000);
});
function DownloadPdf() {
window.location = "#Url.Action("CreatePdf", "Home")";
}
</script>
I would suggest :
public ActionResult ControllerAction1()
{
return View();
}
For the View(), for document.ready function :
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Action2", "Controller")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
.success(function(result) {
// return true or false
// html of json result
})
.error(function(xhr, status) {
});
});
Related
I'm new to MVC. I got a situation where I need to pass a parameter from view to controller on the button click (the button is in partial view), which then renders another partial view in the same page.
Steps followed:
I used jquery button click event for the button of partial view.
I made an ajax call to pass the parameters from my view to the controller.
The following is my code:
$(document).on("click", "#btninPartialView", function(e){
var data = $("txtinPartialView").val();
$("#mainPageContainer").load("/Controller/Action", data, function(){
$.ajax({
//url: #Url.Action("Action", "Controller"),
type: GET,
data: {
id: data
},
success: function(){
}
error: function(){
}
})
}
})
Problem:
The problem is that, the data I'm received in the action method is null.
Please let me know if I'm missing anything.
Thanks in advance.
$(document).on("click", "#btninPartialView", function(e){
var data = $("txtinPartialView").val();
$.ajax({
url: "/Controller/Action",
type: GET,
data: {
id: data
},
success: function(result){
$("#mainPageContainer").html(result);
}
error: function(){
})
})
This should work.
Please check with the arguments your Action method is accepting.
for example if signature is
public ActionResult Action1(string name)
then you need to pass the data as
var data = { name : $("txtinPartialView").val() }
The problem is that you are mixing both jquery ajax and load function, load function sends an ajax call behind the scenes, so you need to use one of them, not both, so try like:
$(document).on("click", "#btninPartialView", function(e){
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: GET,
data: {
id: $("txtinPartialView").val()
},
success: function(response){
$("#mainPageContainer").html(response);
},
error: function(){
}
});
});
i am a new in using MVC3 Razor syntax and i have a view that containing a dropdownlist and i want when the user change the value of it , a function in the controller that take selected value as a parameter will be executed automatically.
this is the code that i wrote in the view and i have a compilation error in that line at runtime:
#Html.DropDownList("DONOR_BLOOD_GROUPE_ID", "--Select--", new {onchange="FilterdIndex(this.value)"})
"DONOR_BLOOD_GROUPE_ID" is in the viewBag and this is the function in the controller that i want to call .
public ViewResult FilterdIndex(int id)
{
var donor = db.DONOR.Include(d => d.BLOOD_GROUP);
var DONOR_BLOOD_GROUPE_ID = from BG in db.BLOOD_GROUP
select new
{
BG.GROUP_ID,BG.GROUP_NAME,
Checked=(BG.GROUP_ID==id)
};
ViewBag.DONOR_BLOOD_GROUPE_ID = DONOR_BLOOD_GROUPE_ID;
return View(donor.ToList());
}
this is javascript code it executes the controller function correctly but i don't know why after returning to the view i have the error msg in this line :
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
and this is the whole function:
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
if ($("#DONOR_BLOOD_GROUPE_ID").val() != "Select") {
var DONOR_BLOOD_GROUPE = {};
DONOR_BLOOD_GROUPE.url = '#Url.Action("FilterdIndex", "DONOR")';
DONOR_BLOOD_GROUPE.type = "POST";
DONOR_BLOOD_GROUPE.data = JSON.stringify({ id: $("#DONOR_BLOOD_GROUPE_ID").val() });
DONOR_BLOOD_GROUPE.datatype = "html";
DONOR_BLOOD_GROUPE.contentType = "application/json";
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
$.ajax(DONOR_BLOOD_GROUPE);
}
});
});
</script>
and this is the line that causes the exception in "DONOR[dynamic]" file
<select AutoPostBack="True" id="DONOR_BLOOD_GROUPE_ID" name="DONOR_BLOOD_GROUPE_ID" onchange="FilterdIndex(this.value)"><option value="">--Select--</option>
I assume you come from a WebForms background where this sort of thing happens all the time with 'Events' this sadly is not how MVC works.
To do what you are trying to do, you will need to create a jquery method for the onchange event of that drop down, then do an async post to your controller.
Have a look at this tutorial which should point you in the right direction
http://www.c-sharpcorner.com/UploadFile/4b0136/working-with-dropdownlist-in-mvc-5/
Hi Asmaa Rashad you can try using this way and your action Method which you are calling using Ajax must be of type JsonResult.
<script type="text/javascript">
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("FilterdIndex", "DONOR")',
dataType: 'json',
data: { id: $("#DONOR_BLOOD_GROUPE_ID").val() },
success: function (data) {
},
error: function (ex) {
alert('Failed to retrieve + ex);
}
});
return false;
})
});
</script>
For reference you can check this blog creating-simple-cascading-dropdownlist-in-mvc-4-using-razor
I have a partial view that contains all my buttons and it needs to display updated values after a form is submitted. At the submission I already have it rendering another partial view, is there a way to make it work where on success of that one being rendered it re-renders. Here is the code I am trying to get to work now based on what I've seen in other places.
jQuery in my view:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#ChangeGrade').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#HeatGradeDiv').find('input[name="grade"]').first().val();
var newname = $('#HeatGradeDiv').find('input[name="updatedGrade"]').first().val();
var heatname = $('#HeatGradeDiv').find('input[name="hiddenHeat"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
grade: origname,
updatedGrade: newname,
hiddenHeat: heatname
},
url: '#Url.Action("ChangeGrade","Home")',
success: function (result) { success(result); }
});
});
function success(result) {
$('#HeatGradeDiv').dialog('close');
$("#Partial_Chem_Analysis").html(result);
//ajax call I'm trying to get working
$.ajax({
type: "POST",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});
}
});
</script>
Here is the controller method I'm calling. When I run it now it is not getting hit.
public ActionResult ButtonsPartial()
{
ButtonsModel B = new ButtonsModel();
B.GetData(searchQ);
return PartialView(B);
}
Any help is appreciated.
If you attach it to a debugger such as (chrome developer tools or firebug) are you seeing any http or js errors?
It looks like you might need to make it a GET rather than POST...
$.ajax({
type: "GET",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});
How to return another view of the same controller? I made some debugging for the application: the ajax method calls the controller action, pass the parameter, executes the instructions. At the
return View("GetEmployeeDays", model);,
the "GetEmployeeDays" view receives the values from model and is populated, but finally in the browser I receive the initial view (from I made the request) - not the GetEmployeeDays view
routing code from Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
JQuery code that calls the action controller's and pass a parameter:
<script type="text/javascript">
$(document).ready(function () {
$('li').click(function () {
$.ajax({
url: '#Url.Action("GetEmployeeDays", "ApproveWork")',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { userCode: $(this).attr('id') }
})
});
});
Controller action that should render the GetEmployeeDays view:
[HttpGet]
public ActionResult GetEmployeeDays(string userCode)
{
.....
return View("GetEmployeeDays", model);
}
If you want to simply load something to a part of your page without reloading to a new page, you should update the specific part of your page in the callback of your ajax function.
$(function(){
$('li').click(function () {
var uCode=$(this).attr("id");
$.get("#Url.Action("GetEmployeeDays","ApproveWork")?userCode="+uCode,
function(response){
$("#DivToBeUpdated").html(response);
});
});
});
If you want to redirect to a new view, you should do it by updating the location.href property value.
$(function(){
$('li').click(function () {
var uCode=$(this).attr("id");
var url="#Url.Action("GetEmployeeDays","ApproveWork")?userCode="+uCode;
window.location.href=url;
});
});
});
Without knowing what your original view is that is being re-rendered, I'd say that most likely your issue is that you should be returning this as a PartialView, since you are making an Ajax request. In addition, it doesn't look like you are actually rendering the result anywhere. What is your fiddler response? Does it show returned HTML? If it does, you probably just need to dump it onto the page by utilizing the .done callback within $.ajax.
<script type="text/javascript">
$(document).ready(function () {
$('li').click(function () {
$.ajax({
url: '#Url.Action("GetEmployeeDays", "ApproveWork")',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { userCode: $(this).attr('id') }
}).done(function() {
$(this).addClass("done");
});
});
</script>
You can't redirect via ajax request. Try a simple GET request:
<script type="text/javascript">
$('li').on('click', function()
{
document.location.href = '#Url.Action("GetEmployeeDays", "ApproveWork")' + '?param1=val1¶m2=val2';
});
</script>
The controller is fine as it is now.
EDITED: Updated as requested
?Building from #David Diez, you can append parameters to your request as follows:
<script type="text/javascript">
$('li').on('click', function()
{
document.location.href = '#Url.Action("GetEmployeeDays", "ApproveWork", new { caseSensativeParamName = "foo" })';
});
</script>
You can, of course, go a JavaScript route as well. Something like this should work:
<script type="text/javascript">
$('li').on('click', function()
{
var targetUrl = '#Url.Action("GetEmployeeDays", "ApproveWork")';
var yourParam = $("#input-id").val();
targetUrl = targetUrl + '?yourServerParamName=' + yourParam;
document.location.href = targetUrl;
});
</script>
Cheers.
I'm trying to execute my controller from javascript using jquery... here is my jquery code that is executing..
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(msg) {
var obj = msg.deserialize();
alert(msg);
}
});
});
</script>
Now it does execute my action..
Here is a sample of my controller class it is executing..
[AcceptVerbs(HttpVerbs.Post)]
[Url("Account/LogOn")]
public virtual ActionResult LogOn(string Username, string Password) {
if (Username == "test") {
return Json(new {
Success = true
});
} else {
return Json(new {
Success = false
});
}
}
Problem is.. when I run the method.. it just tries to download a "Logon" file which contains the result.. how do I put it back to an object in jquery so i can handle it the correct way, I've tried adding the success tag and attempt to check the msg but it doesnt even run it
Put your script inside document.ready before attempting to register any event handlers as the DOM might have not loaded yet:
<script type="text/javascript">
$(function() {
// ... copy - paste your script here
});
</script>
Also you don't need to set the dataType, jQuery knows it from the Content-Type response header from the server. Another remark: the msg object passed to the success handler is already a JSON object: you don't need to parse/deserialize it:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(msg) {
alert(msg.Success);
}
});
return false;
}
});
</script>
And the solution I would recommend you is to use the jquery.form plugin. Thanks to it your js code will look as easy as:
<script type="text/javascript">
$(function() {
$('form').ajaxForm(function(msg) {
alert(msg.Success);
});
});
</script>
Very neat stuff. You don't need to bother about serializing/deserializing data, preventing default events, it can even handle file uploads.
HIDDENHANCEMENT
var obj = msg.deserialize();
If that is not a joke, you would have spotted a hidden feature :)
If you're using jQuery v.1.4.x you don't need to parse a JSON string manually.
Using an older version, try
var obj = window.JSON.parse(msg);