Asp.Net MVC Routing and URL Issue - c#

Firstly, thank you for your answers. I have a problem about routing on Asp.Net MVC.
You can see my solution here on the photo where my controllers and views located. I would like to open "UserProfile.cshtml" from "Index.cshtml". Well, my first approach is using Ajax to post "UserProfile Action" in ProfileController.
$.ajax({
url: "/Profile/UserProfile",
type: "POST",
dataType: "json"})
.done(function(response){
window.location = '/Profile/UserProfile'});
this code blocks goes to controller and hits the "UserProfile" Action but returns no error and no view. Even URL doesn't change.
public ActionResult UserProfile()
{
return View ();
}
I would highly appreciate your helpful answers and support. Thank you!

First, you need to have Razor (.cshtml) views, not aspx for mvc to be able to serve these pages out of the box. If you have a controller action named UserProfile in a ProfileController and call return View(), then mvc will be default try to return the view located at Views/Profile/UserProfile.cshtml (it will actually also check a couple other locations such as the Views/Shared/ folder for the view). The following should work for you:
//located in ProfileController
[HttpPost]
public ActionResult UserProfile()
{
return View();
}
//located at Views/Profile/UserProfile.cshtml
`<h4>you've found your user profile page!</h4>`
If you're trying to hit this view by ajax- then you'll need to attack the problem from a slightly different direction. Redirecting on the server side will not work with ajax since it is asynchronous. You can achieve this by using the .done() ajax callback something like the following:
$.ajax({
url: "/Profile/UserProfile",
type: "POST",
dataType: "json"
}).done(function(response){
window.location = '/Profile/UserProfile'
});

Related

HttpPost to MVC partial view?

Allow me to preface this by saying that I did look into other SO questions dealing with this matter, but they were either ASP solutions or not quite exactly what I needed.
My question is as follows, can I make an Http Post request to a method in my controller that returns a partial view if I am using Html.BeginForm? I know, and have used, POST methods using BeginForm multiple times, however, those were to ActionResult methods which were responsible for transferring the data stored over into the server. What I would like to do is something as follows:
Say I have this cshtml:
<div class="test">
#using (Html.BeginForm("MyPartialViewMethod"), FormMethod.POST) {
#Html.LabelFor(x => x.StartTimeLabel, Model.StartTime);
#Html.TextBoxFor(x => x.StartTime);
<input type="button" value="Submit"/>
}
</div>
Such that in my Controller I could say have the following example method.
[HttpPost]
public PartialViewResult MyPartialViewMethod(Model DynamicDataModel) {
//Pass the data in the DynamicDataModel into a new cshtml page and
//have the partial view it returns be rendered on screen
}
So in a nutshell:
Make POST request to server passing into it my data values
Have server process the data and return the partial view accordingly populated with all the required data.
I imagine that I could take the approach I used to do back in college with php which is AJAX call via JS to php, php spits out html, JS adds the html where it is needed. However, this seems to be a bit too rough.
yes you can.
you can also do it in ajax with a custom submit buton who call your ajax an jquery,
with something like that and serialize your model.
or just take the controller part if no ajax and submit
$.ajax({
url: '#Url.Action("actionName", "controllerName")',
data: $('#MyPartialViewMethod').serialize(),
dataType: "json",
type: 'POST',
success: function (data) {
$('html').html(data);
},
error: function (request, error) {
}
});
[HttpPost]
public actionName(Model myModel)
{
do thing with your model
return PartialView(myModel);
}
an loop

Load a Partial View using jQuery .load() and no Razor

I have a View which is the container for a PartialView. Let's say a Customer - Orders relation. The View should received a CustomerViewModel whereas the PartialView a collection of Orders, such as IEnumerable<OrderViewModel>.
I basically have two ways of doing this (not to mention Angular), either Razor or jQuery. With Razor was pretty straightforward by utilizing #Html.Partial("_CustomerOrdersPartial", Model.Orders). But let's assume I cannot use Razor syntax and here it is how I ended up posting this question. I have read many posts on this matter but, most of them (not to mention all), suggest to use $("#container").load('#Url.Action("ActionName", new { parameterX = valueY })). Then here are my questions:
Why to mix Razor and jQuery?
Is this the only way?
Is there any way to call the View and pass the model?
The last question has to do with the fact that the above code requires an action on the server-side to be called, whereas the #Html.Partial("_CustomerOrdersPartial", Model.Orders) mentioned above will just call the View (client-side) and send the given Model in.
Any idea on how to solve this would be really helpful.
Thanks in advance for your time and thoughts.
my solution is:
function ReturnPanel(div, panel) {
$.ajax({
type: "POST",
url: "#Url.Action("GetPanel", "ControllerName")",
data: JSON.stringify({ 'idCurso': idCurso, 'panel': panel }),
contentType: 'application/json; charset=utf-8',
success: function (response) {
$("#" + div).html(response);
},
error: function (xhr, status, errorThrown) {
//Here the status code can be retrieved like;
alert("Error: status = " + xhr.status + " Descripcion =" + xhr.responseText);
}
})
}
in cs.
[HttpPost]
public ActionResult GetPanel(int idCurso, string panel)
{
Contenido contenido = new Contenido();
contenido.IdCurso = idCurso;
return PartialView(panel, contenido);
}
This code should do it. The trick is to acquire the URL and then make sure you get the parameter list right. I used a little Razor to get the URL but you don't have to. Also, If you fail to match the parameter list, your call will not even be acknowledged. You have been warned. I tried to name every thing in a way that helps.
var url = '/controllerName/ActionName';
$('#pnlFillMee').load(url, {NameOfParam: $('#elementID').val() },
function () {CallMeAfterLoadComplete(); });
Here's a real world example I use at work. ReviewInfo is an action in the
controller associated with this page. It returns a partialview result.
$(document).ready(function () {
var url = '/supervisor/reviewinfo';
$('#pnlReviewInfo').load(url, { FCUName: $('#FCU').children(':selected').text(), AccountsFromDate: $('#AccountsFrom').val()}, function () {
InitializeTabs(true);
});
});
This goes somewhere on your form.
<div id="pnlReviewInfo" style="width: 85%"></div>
EDIT:
I would also look up the other jQuery functions like $.get, $.post and $.ajax which are more specialized versions of $.load. and see this link which might answer all your questions about passing models:
Pass Model To Controller using Jquery/Ajax
Hope this helps
wrapping up this question and thanks to #stephen-muecke and #charles-mcintosh for their help:
Using #Html.Partial(partialViewName) the server returns a string resulting from the partial view passed in. Preferred method if you need to manipulate the partial before being displayed. Otherwise, using #Html.RenderPartial(partialViewName) will write into the stream output sent to the browser, the HTML code from the given partial.
As per jQuery API, $(elem).load(url[,data][,complete]) will place the returned HTML into the matching element. Thus, it requires an action method for the given url.
If for whatever reason Razor cannot be used on the UI, chances are you would likely end up either hard-coding the url like in the sample code provided above by #charles-mcintosh or using Angular.

Download a File by POST (HttpPost action) on ASP.NET MVC controller action using Javascript

Initially, my controller action accepts GET. When my data grew, I was forced to move to POST method to be able to send larger data.
My controller action is as follows:
[HttpPost]
public ActionResult ClausesPdf(MyArrayModel obj)
{
...
return File(pdf, "application/pdf", "file.pdf");
}
How can I call this action and download the file using javascript?
Update: I realized that my original answer about AJAX was not entirely accurate since there is no way to return a file from an AJAX call. I suggest that you look at this SO question: Download Excel file via AJAX MVC. I believe #CSL has a good answer that is similar to what you want.
My answer is not plain javascript. This is an AJAX call in jQuery on how it could be done there:
$.ajax({
url: urlControllerAction,
type: 'POST',
cache: false,
data: //your parameter data here
})
.done(
function(result, textStatus, jqXHR) {
//do something with the "result"
}
)
.fail(
//what should be done if something goes wrong
);

Getting AJAX to not load a new page after submitting a form and instead render a partial view or nothing

I'm in a bit of a bind here, I am trying to submit a form using ajax, all goes well and dandy until after the server has done it's thing, it decides to load to the action onto a new page, which is exactly what I do not want.
Here is my controller
[HttpPost]
public ActionResult Submit(int id, string trainingProgramId, FormCollection form, User user)
{
//Do Some action
return null;
}
In a different controller I have it set up to do $return PartialView(model);
this is the JQuery code that I am using.
$(function () {
$("form").submit(function (e) {
if (nextquestion()) { //check if posting can proceed
$.ajax({
type: "POST",
data: $(this).serialize(),
url: $(this).attr("action"),
success: function (response) {
alert(response);
$('#cases:last-child').insertAfter(response);
},
error: function (data) { }
});
}
e.preventDefault();
});
});
In all cases I am being redirected to a different url after performing the operation. Which is not the intention, especially if my intention might be to load more stuff into the page.
I've been tring everything, a bunch of solutions, but once my controller does a return statement the page automatically reloads to $/Submit
I have added $ #Scripts.Render("https://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js"); to my scripts
From any other example I am finding this should work as I want it to, by remaining on the same page, however I am finding it difficult to understand who is responsible for changing the page either way. When I return my PartialView, a completely new page loads with the model as I've had it set up for the Partial View to be inserted originally.
Anyone care to explain what is going on or why my code is wrong?
I can't find it after a whole day of trying to debug.

HttpRuntime.Cache collection is empty when action is invoked by Ajax

I am trying to figure out why my HttpRuntime.Cache collection is always empty when controller action is invoked by $.ajax? In actions invoked normally everything works perfectly and I can get my data from Cache. Maybe actions invoked by AJAX have some different lifecycle and Cache collection is not ready yet? This is my example code:
action:
[HttpPost]
public PartialViewResult SomeAjaxAction()
{
// when receive ajax request HttpRuntime.Cache is always empty, but it shouldn't be
SomeType item = HttpRuntime.Cache.Get("cache_key") as SomeType;
return PartialView("SomeAjaxActionView", item);
}
invocation:
$.ajax({
type: 'POST',
url: '/controller/SomeAjaxAction/',
success: function (response) {
alert(response);
}
});
Is there any way to fix it e.g by custom action filter?
ANSWER
Ok, I found answer here: Access to session when making ajax call to Asp.net MVC action So I imporoved my code with base.HttpRuntime.Cache.Get("key") and it works as expected!
Ok, I found answer here: Access to session when making ajax call to Asp.net MVC action So I imporoved my code with base.HttpRuntime.Cache.Get("key") and it works as expected!

Categories