I am beginning developer in asp.Net MVC5.
In my MVC project i use with web service that return me a string URL the URL is from another domain.
I want to move to the URL.
For clear myself:
The client fill form home page and press submit, in the server side i send a request web
service with parameters from the form and get URL with another domain and this URL i need to present as second page to the client
public class HomeController : Controller
{
public ActionResult Home()
{
return View("~/Views/Home/home.cshtml");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult doSomething(Something obj)
{
//use web service and get string URL
string urlString = ;// get from the web service response.
return View();// want write in the ();
}
}
Also this is usefull for navigation in MVC.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult doSomething(Something obj)
{
//use web service and get string URL
string urlString = ;// get from the web service response.
if (!string.IsNullOrEmpty(urlString))
{
//if the url is from within the domain.
return RedirectToAction(urlString);
//if the url is from other domain use this
//return Redirect(urlString);
}
//If the urlString is empty Return to a error page
return View("Error");
}
The url is from another site not the same domain
If you want to redirect to an external URL, you will need to use the Redirect() method.
Like so:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DoSomething(Something obj)
{
// Use web service to get the string URL
string urlString = ...;
if (string.IsNullOrEmpty(urlString))
{
// If the urlString is empty, take the user to an Error View.
return View("Error");
}
// Redirect the user to the urlString
return Redirect(urlString);
}
I would recommend also doing some checking to ensure the URL is definitely valid. You can do this using the Uri static method, IsWellFormedUriString() - this returns a bool.
Like so:
if (!Uri.IsWellFormedUriString(urlString, UrlKind.Absolute))
{
// If the urlString is not a well-formed Uri, take the user to an Error View
return View("Error");
}
// Redirect the user to the urlString
return Redirect(urlString);
Alternatively, if you're redirecting to an internal Action, use the RedirectToAction() method, as #ankur suggested.
As an extra note: Ensure that your C# method names use PascalCase. Conserve camelCase for local variables/private fields.
So, you would use DoSomething(...), instead of doSomething(...) (I've done this in my example).
Hope this helps.
Related
I'm using ASP.NET MVC 4. I am trying to pass data from one controller to another controller. I'm not getting this right. I'm not sure if this is possible?
Here is my source action method where I want to pass the data from:
public class ServerController : Controller
{
[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
XDocument updatedResultsDocument = myService.UpdateApplicationPools();
// Redirect to ApplicationPool controller and pass
// updatedResultsDocument to be used in UpdateConfirmation action method
}
}
I need to pass it to this action method in this controller:
public class ApplicationPoolController : Controller
{
public ActionResult UpdateConfirmation(XDocument xDocument)
{
// Will add implementation code
return View();
}
}
I have tried the following in the ApplicationPoolsUpdate action method but it doesn't work:
return RedirectToAction("UpdateConfirmation", "ApplicationPool", new { xDocument = updatedResultsDocument });
return RedirectToAction("UpdateConfirmation", new { controller = "ApplicationPool", xDocument = updatedResultsDocument });
How would I achieve this?
HTTP and redirects
Let's first recap how ASP.NET MVC works:
When an HTTP request comes in, it is matched against a set of routes. If a route matches the request, the controller action corresponding to the route will be invoked.
Before invoking the action method, ASP.NET MVC performs model binding. Model binding is the process of mapping the content of the HTTP request, which is basically just text, to the strongly typed arguments of your action method
Let's also remind ourselves what a redirect is:
An HTTP redirect is a response that the webserver can send to the client, telling the client to look for the requested content under a different URL. The new URL is contained in a Location header that the webserver returns to the client. In ASP.NET MVC, you do an HTTP redirect by returning a RedirectResult from an action.
Passing data
If you were just passing simple values like strings and/or integers, you could pass them as query parameters in the URL in the Location header. This is what would happen if you used something like
return RedirectToAction("ActionName", "Controller", new { arg = updatedResultsDocument });
as others have suggested
The reason that this will not work is that the XDocument is a potentially very complex object. There is no straightforward way for the ASP.NET MVC framework to serialize the document into something that will fit in a URL and then model bind from the URL value back to your XDocument action parameter.
In general, passing the document to the client in order for the client to pass it back to the server on the next request, is a very brittle procedure: it would require all sorts of serialisation and deserialisation and all sorts of things could go wrong. If the document is large, it might also be a substantial waste of bandwidth and might severely impact the performance of your application.
Instead, what you want to do is keep the document around on the server and pass an identifier back to the client. The client then passes the identifier along with the next request and the server retrieves the document using this identifier.
Storing data for retrieval on the next request
So, the question now becomes, where does the server store the document in the meantime? Well, that is for you to decide and the best choice will depend upon your particular scenario. If this document needs to be available in the long run, you may want to store it on disk or in a database. If it contains only transient information, keeping it in the webserver's memory, in the ASP.NET cache or the Session (or TempData, which is more or less the same as the Session in the end) may be the right solution. Either way, you store the document under a key that will allow you to retrieve the document later:
int documentId = _myDocumentRepository.Save(updatedResultsDocument);
and then you return that key to the client:
return RedirectToAction("UpdateConfirmation", "ApplicationPoolController ", new { id = documentId });
When you want to retrieve the document, you simply fetch it based on the key:
public ActionResult UpdateConfirmation(int id)
{
XDocument doc = _myDocumentRepository.GetById(id);
ConfirmationModel model = new ConfirmationModel(doc);
return View(model);
}
Have you tried using ASP.NET MVC TempData ?
ASP.NET MVC TempData dictionary is used to share data between controller actions. The value of TempData persists until it is read or until the current user’s session times out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request.
The code would be something like this:
[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
XDocument updatedResultsDocument = myService.UpdateApplicationPools();
TempData["doc"] = updatedResultsDocument;
return RedirectToAction("UpdateConfirmation");
}
And in the ApplicationPoolController:
public ActionResult UpdateConfirmation()
{
if (TempData["doc"] != null)
{
XDocument updatedResultsDocument = (XDocument) TempData["doc"];
...
return View();
}
}
Personally I don't like to use TempData, but I prefer to pass a strongly typed object as explained in Passing Information Between Controllers in ASP.Net-MVC.
You should always find a way to make it explicit and expected.
I prefer to use this instead of TempData
public class Home1Controller : Controller
{
[HttpPost]
public ActionResult CheckBox(string date)
{
return RedirectToAction("ActionName", "Home2", new { Date =date });
}
}
and another controller Action is
public class Home2Controller : Controller
{
[HttpPost]
Public ActionResult ActionName(string Date)
{
// do whatever with Date
return View();
}
}
it is too late but i hope to be helpful for any one in the future
If you need to pass data from one controller to another you must pass data by route values.Because both are different request.if you send data from one page to another then you have to user query string(same as route values).
But you can do one trick :
In your calling action call the called action as a simple method :
public class ServerController : Controller
{
[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
XDocument updatedResultsDocument = myService.UpdateApplicationPools();
ApplicationPoolController pool=new ApplicationPoolController(); //make an object of ApplicationPoolController class.
return pool.UpdateConfirmation(updatedResultsDocument); // call the ActionMethod you want as a simple method and pass the model as an argument.
// Redirect to ApplicationPool controller and pass
// updatedResultsDocument to be used in UpdateConfirmation action method
}
}
I have Web API, I have written action method. but it's not correctly visible when I run the application. I cannot see SendPushNotification in the attached image.
Controller Code:
[RoutePrefix("api/OTP")]
public class OTPController : ApiController
{
public IHttpActionResult Get(int id)
{
return Ok("value");
}
[HttpGet]
public IHttpActionResult SendPushNotification(string userId, string factorId, string domain)
{
var response = _oTPRepository.SendPushNotification(userId, factorId, domain);
return Ok(response);
}
add a Route over your method, something like this:
[HttpGet]
[Route("SendPushNotification")]
public IHttpActionResult SendPushNotification(string userId, string factorId, string domain)
{
var response = _oTPRepository.SendPushNotification(userId, factorId, domain);
return Ok(response);
}
This will combine with the RoutePrefix from your controller and give you what you want.
You can call it whatever you want as well, whatever makes sense for your API.
in mentioned image second method is that for which you are actually looking for.
default routing for action methods is api/{controller_name}.
if you want to access that method as your given name you have set routing attribute above that action method.
like [Routing("api/OTP/SendPushNotification")]
My action method returns a view. It looks like the following.
public public ActionResult Init(string additionalParams)
{
Response.AddHeader("additionalParams", additionalParams);
return View(model);
}
The view has a form. The form is submitted to another action method
[HttpPost]
public ActionResult InitPost(MyModel model)
{
string additionalParams = Request.Headers.Get("additionalParams"); <--- getting null
}
how do i get the additionalParams in the post? Please help.
So on the Init(), I was using Route attribute routing, that makes urls look like this http://wwww.example.com/23/22/... Apparently this caused issues with the length of url. So I switched to using query string, by removing the route attribute routing. Now with this url, I can pass my additionalParams just fine, http://www.example.com?id=222&otherID=222&additionalParams="whatever"
I have MVC project that use with web service to get a url and then do a redirect to the URL that i get.
In the first request(the request that return me the URL in the response) i need provider some details and one of them is successUrl.
successUrl is URL that if the action of the client in the URL that i was redirect before success so redirect to successUrl.
My question is: it possible to redirect to ActionResult? if yes What i need to send in successUrl?
Update
For Example:
I have my MVC Project and Web Service.
My controller-
public class HomeController : Controller
{
public ActionResult Home()
{
return View("~/Views/Home/home.cshtml");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CheckObject(someObject obj)
{
if (ModelState.IsValid)
{
ResponseWS responseWs = wsRequest(deatils);
}
}
[HttpPost]
public ActionResult doSomething()
{
//....do something...
}
}
The steps-
First the client go to home page from ActionResult Home().
The client fill form and click submit and go to
ActionResult CheckObject(someObject obj)
From ActionResult CheckObject(someObject obj) send request to WS
with parameters that one of them urlSuccees.
Ws return response with URL(for the example www.test.com) that i
need to redirect to it.
I do the redirect to www.test.com.
The client do something and if the client action was success the
www.test.com need to redirect to my urlSuccees.
NOTE: I want that urlSuccees will be ActionResult doSomething()
Thanks,
Tal
I created a web api controller that has an register action:
public class MyProjApiController : ApiController
{
public IHttpActionResult Register()
{
return RedirectToAction("Register", "AccountController"); //??
}
}
And I am trying to redirect to another action in MVC Controller public class AccountController : Controller that has public async Task<ActionResult> Register(RegVM model) but my Register action in MyProjApiController has IHttpActionResult return type and register in AccountController has Task<ActionResult> type - how to call it?
I think you are mixing two concepts here. Your API controller should have endpoints which will be called from some client and you should be returning some data back in a format which client can read, XML or JSON. You should not be doing a redirect to another MVC controller.
What you should be doing is return some data which has the path to the MVC action controller which the client can use.
public HttpResponseMessage Register()
{
//DO something as you want
var newUrl = this.Url.Link("Default", new { Controller = "Account",
Action = "Register" });
return Request.CreateResponse(HttpStatusCode.OK,
new {Success = true, RedirectUrl = newUrl});
}
This will return you a response like this to the caller with 200 OK response status code
{
"Success" : true,
"RedirectUrl" : "yoursite.com/Account/Register"
}
The client should read this and do the necessary things. For example, If you are calling this API from your js code, You can simply use window.location.href to redirect the user to the new page.
For example ,
$.post("PathToYourApiEndpoint",function(res){
if(res.Success)
{
window.location.href = res.RedirectUrl;
}
});
Again,I am not sure why you are calling the API first and the redirecting the user to the MVC controller action. Whatever logic you are doing in the Web api action method, you might be able to do in your MVC controller and thus avoid your API call.
If you mean from the API help file. I wanted to disable except for local.
if (!Request.IsLocal)
{
Response.Redirect("/home");
}