I am really confused,
here is the code :
[HttpPost]
public ActionResult Settings(string SubmitButton)
{
if (SubmitButton == "Sign In") {
ServiceLocator.Current.GetInstance<IAppContext>().LoggedUser = null;
Response.Cookies["loginuser"].Expires = DateTime.Now;
return RedirectToAction("Logon", "Account");
}
if (SubmitButton == "Sign Up") { return RedirectToAction("register", "Account"); }
if (SubmitButton == "Change Default Ride Settings") { return RedirectToAction("changeSettings", "Home"); }
return View();
}
The view contain
<% using (Html.BeginForm()) { %>
Three input ,
<% } %>
the controller is not fired with httppost but fired with httpget
You probably need to pass in the controller and action names in Html.BeginForm() in your view. Since the [HttpPost] Settings() action is being invoked for HTTP get requests, that implies that there isn't another Settings() action for get requests, so I'm guessing that your view is being served from a different action. In such a case, you need to explicitly set the controller and action in your Html.BeginForm(). Try this:
<% using (Html.BeginForm("Settings", "YourControllerName")) { %>
You have to generate a html form with the method attribute set to post if you want a post to happen:
Html.BeginForm("action","controller", FormMethod.Post) { ... }
There should be action with name Index() and should not containg any parameters in it. This is the problem I have faced.
I have used ActionName() to solve the same problem,
Not working code:
[HttpGet]
public ViewResult RsvpForm()
{
[HttpPost]
public ViewResult RsvpFrom()
{
}
Working code:
[HttpGet]
public ViewResult RsvpForm()
{
}
[HttpPost, ActionName("RsvpForm")]
public ViewResult RsvpFromPost()
{
}
The proper way using razor
#using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { id = "form1" }))
{
//form content
}
Related
I've working on MVC 4 application and want to redirect back with message to call action view:
Action that called : Upload
Current view : Index
public class HospitalController: Controller {
public ActionResult Index()
{
return View(Model);
}
[HttpPost]
public ActionResult Index(Model model)
{
return View(ohosDetailFinal);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
// return View(); not working
}
}
#using (Html.BeginForm("Upload", "Hospital", null, FormMethod.Post, new { enctype = "multipart/form-data", #class = "" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<input type="file" id="dataFile" name="upload" class="hidden" />
}
Thanks !
Follow the PRG pattern. After successful processing, redirect the user to another GET action.
You can return a RedirectResult using RedirectToAction method. This will return a 304 response to the browser with the new url in the location header and the browser will make a new GET request to that url.
[HttpPost]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//to do : Upload
return RedirectToAction("Index","Hospital",new { msg="success"});
}
Now in the Index action, you may add this new parameter msg and check the value of this and show appropriate message. The redirect request will have a querystring with key msg (Ex :/Hospital/Index?msg=success)
public ActionResult Index(string msg="")
{
//to do : check value of msg and show message to user
ViewBag.Msg = msg=="success"?"Uploaded successfully":"";
return View();
}
and in the view
<p>#ViewBag.Msg</p>
If you do not prefer the querystring in the url, you may consider using TempData. But tempdata is available only for the next request.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
return Index();//or with model index
}
Try the below code, Hope It helps.!
View
#using (Html.BeginForm("Upload", "Hospital", null, FormMethod.Post, new { enctype = "multipart/form-data", #class = "" }))
{
if (TempData["Info"] != null)
{
#Html.Raw(TempData["Info"])
}
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<input type="file" id="dataFile" name="upload" class="hidden" />
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
TempData["Info"]="File Uploaded Successfully!";
return RedirectToAction("Index");
}
When user click this element, I want catch id data in controller or in OnActionExecuting method in ActionFilter class.
How I can do this?
In view:
<a id="123" href="AreaName/ControllerName">TEST</a>
You could try this...
In Controller:
public ActionResult Index()
{
var model = new HomeViewModel { Id = 123 };
return View(model);
}
public void RecordClick(int id)
{
int incomingId = id;
}
In View:
#Html.ActionLink("Link Text", "RecordClick", "Home", new { id = #Model.Id }, null)
Generated HTML:
Link Text
Upon clicking link, id value will be sent to RecordClick action.
TEST
your controller
[HttpGet]
public ActionResult Index(int userid)
{
return View();
}
if you debug you should have that value
I have a problem with ASP.NET MVC 4 application.
I have a partial view with fallowing code:
<li>#using (Html.BeginForm("LogOff", "Account", FormMethod.Post,
new { id = "logoutForm", style = "display: inline;" }))
{
#Html.AntiForgeryToken()
Log out
}
</li>
And after i click "Log out" im redirected to: /Account/Login?ReturnUrl=%f2Account%f2LogOff and going to action:
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login()
{
ViewBag.Title = loginTitle;
return View();
}
But i want to handle this in action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
Session["user"] = null;
return RedirectToAction("Index", "Index");
}
Can you help me?
It looks like you are not logged in during logging off.
From a page I have the following:
#using (Html.BeginForm("AddEntry", "Configure", FormMethod.Get, new { returnUrl = this.Request.RawUrl }))
{
#Html.TextBox("IP")
#Html.Hidden("TypeId", 1)
<input type="submit" value="#Resource.ButtonTitleAddComponent" />
}
so controller is called correctly:
public ActionResult AddEntry(string ip, int TypeId, string returnUrl)
{
// Do some stuff
return Redirect(returnUrl);
}
My problem is that returnUrl gets null and it does not redirect to the same page that called the controller. Ideas?
Using: ASP.NET MVC 4
Razor
you can also do this if you need to return to something like details page and return to the same page with a query:
return Redirect(Request.UrlReferrer.PathAndQuery);
You can get the Refer URL from the Request in the controller:
public ActionResult AddEntry(string ip, int TypeId, string returnUrl)
{
// Do some stuff
string url = this.Request.UrlReferrer.AbsolutePath;
return Redirect(url);
}
This will redirect you exactly to the calling URL.
You could use a Request.QueryString method to get some values from URL, for sample:
#using (Html.BeginForm("AddEntry", "Configure", FormMethod.Get, null))
{
#Html.TextBox("ip")
#Html.Hidden("TypeId", 1)
#Html.Hidden("returnUrl", this.Request.RawUrl)
<input type="submit" value="#Resource.ButtonTitleAddComponent" />
}
And in your controller, receive it as a parameter string returnUrl.
in your controller class use Request.UrlReferrer. There's no need to pass the url from the page.
public ActionResult AddEntry(string ip, int TypeId)
{
// Do some stuff
return Redirect(Request.UrlReferrer.ToString());
}
#using (Html.BeginForm("AddEntry", "Configure", new { returnUrl = this.Request.RawUrl }))
{
#Html.TextBox("IP")
#Html.Hidden("TypeId", 1)
<input type="submit" value="#Resource.ButtonTitleAddComponent" />
}
Change your code like this
I found that using UrlReferrer works well and allows me to add on extra params if needed.
Helper method example:
protected RedirectResult RedirectToCurrentUri(String strQueryStringOverride = "")
{
String strReferrer = Request.UrlReferrer.AbsoluteUri;
if (String.IsNullOrWhiteSpace(strReferrer))
{
strReferrer = "/";
}
// Can also override referrer here for instances where page has
// refreshed and replaced referrer with current url.
if (!String.IsNullOrWhiteSpace(strQueryStringOverride))
{
String strPath = (strReferrer ?? "").Split('?', '#')[0];
return Redirect(strPath + strQueryStringOverride);
}
return Redirect(strReferrer);
}
Note that the method allows Query String override.
This can be used as a helper method in any controller as per below:
Redirect without changing query string (if any):
return RedirectToCurrentUri()
Example query string override:
return RedirectToCurrentUri("?success=true")
on Get like Edit(int? id)
ViewBag.RefUrl = Request.UrlReferrer.ToString();
on view #Html.Hidden("RefUrl");
on post Edit(int id,string RefUrl)
return Redirect(RefUrl);
Not sure if I am following MVC conventions but I have some variables passed from one Controller A to Controller B. My objective is to have another view named 'Publish' with an ActionLink to do some processing upon clicking on it.
The redirection from Controller A:
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Publish", new { accTok = facebookAccessTok, fullImgPath = fullpath });
return Json(new { Url = redirectUrl });
I now have the values for 'accTok' and 'fullImgPath' in my 'Publish' Index for Controller B which contains an ActionLink in its View to do the processing, but I am not sure how do I pass them to my 'Publish' ViewResult' method to do it:
namespace SF.Controllers
{
public class PublishController : Controller
{
public ViewResult Index(string accTok, string fullImgPath)
{
return View();
}
// This ViewResult requires the values 'accTok' and 'fullImgPath'
public ViewResult Publish()
{
// I need the values 'accTok' and 'fullImgPath'
SomeProcessing();
return View();
}
public SomeProcessing(string accessToken, string fullImagePath)
{
//Implementation
}
}
}
Index View:
#{
ViewBag.Title = "Index";
}
<h2>Publish</h2>
<br/><br/>
#Html.ActionLink("Save Image", "Publish")
I would suggest doing this
public ViewResult Publish(string accTok, string fullImgPath)
{
SomeProcessing(accTok,fullImgPath);
return View();
}
In your controller:
public ViewResult Index(string accTok, string fullImgPath)
{
ViewModel.Acctok = accTok;
ViewModel.FullImgPath = fullImgPath;
return View();
}
public ViewResult Publish(string accTok, string fullImgPath)
{
SomeProcessing(accTok,fullImgPath);
return View();
}
In the view:
#Html.ActionLink("Save Image", "Publish","Publish",new {accTok=ViewModel.Acctok, fullImgPath=ViewModel.FullImgPath},null )
Instead of the ActionLink you could also make it a form with hidden input fields (if this method changes thing in a database/on disk, it actually should be in a post).
But anyway use a viewmodel to pass the parameters from the index action to the view, so that in turn can send them to the publish action. This is generally the way to do it with the stateless web in MVC.