This is my code
public ActionResult Contact()
{
//var getRequest = (HttpWebRequest)WebRequest.Create("https://brisol.net/av-d");
//var getResponse = (HttpWebResponse)getRequest.GetResponse();
//return new HttpWebResponseResult(getResponse);
return ExternalGet("https://sample.net/av-d");
}
/// <summary>
/// Makes a GET request to a URL and returns the relayed result.
/// </summary>
private HttpWebResponseResult ExternalGet(string url)
{
var getRequest = (HttpWebRequest)WebRequest.Create(url);
var getResponse = (HttpWebResponse)getRequest.GetResponse();
return new HttpWebResponseResult(getResponse);
}
In the above code when i click contact link it open the below url with in the same window,but i want to open new window from mvc controller.
You can use target for blank page
HTML Code
<input type="button" target="_blank"/>
MVC Code
#Html.ActionLink(" ", "ActionName", "ControllerName", null, new { target = "_blank", #class = "btn btn-primary fa fa-list"})
That is not an issue of the MVC. It depends on your HTML code. The link which should be opened in a new window should look like this:
Click me
Please, notice the target attribute. However, keep in mind that it is up to the browser whether it opens new window or just a new tab.
Things like that should be done from the view or from javascript not from the controller.
javascript:
window.open("Link URL")
razor
#Html.ActionLink("bla", "Action", new {controller="Controller"}, new {target="_blank"})
or
bla
New tab/window can be controlled from your html page actually, not from server side code.
Use target='_blank' attribute in your anchor (<a>) tag.
If you are using plain HTML, do:
MDN
For rajor helper, do
#Html.ActionLink("visit the page", "action", "controller", new {target="_blank"})
Here is the help page:
https://developer.mozilla.org/en/docs/Web/HTML/Element/a
Dim strScript As String = "window.open('../Newpage.aspx', 'new_window');"
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Open window", strScript, True)
Below Code will help you
Controller:-
public ActionResult ABC()
{
if(Request.HttpMethod == "POST")
return Redirect("http://www.google.com");
else
return View();
}
View:-
#using (Html.BeginForm("ABC", "Test", FormMethod.Post, new { target = "_blank" }))
{
<input type="submit" value="Contact" id="btnsubmit" />
}
Above example is just give you idea how to open new url from the controller you need to set this idea in your code.
In this example controller is Test , when you post the request like click on Contact then post the view with target = “_blank” so response of the controller action will be open in new window.
Related
Controller
[HttpGet]
[Route("~/search/{clause}/{skip?}")]
public async Task<ActionResult> Search(string clause, int skip = 0)
{
...
}
View
#using (Html.BeginForm("Index", "search", FormMethod.Get))
{
#Html.TextBox("clause", null, new { #class = "form-control col-md-4" })
...
}
Rendered Html
<form action="/search" method="get">
<input id="clause" name="clause" type="text" value="test">
</form>
I am using [HttpGet] partly because i want the search to be accessing via http://myapp.com/search/<search values>
When i navigate to http://myapp.com/search/test, everything seems fine, but when i try to enter my new search term in the textbox and hit enter or submit, it navigates to http://myapp.com/search?clause=newsearch
What should I do so that my textbox will navigate to http://myapp.com/search/newsearch instead?
Your form generates http://myapp.com/search?clause=newsearch because a browser has no knowledge of your routes (c# code running on your server).
In order to generate your preferred url (http://myapp.com/search/newsearch), you need javascript to intercept and cancel the default submit, and build a url to navigate to. Using jQuery:
$('form').submit(function() {
var baseUrl = $(this).attr('action'); // or var baseUrl = '#Url.Action("Index", "search")';
var url = baseUrl + '/' + $('clause').val(); // add value for skip if required
location.href = url; // redirect
return false; // cancel the default submit
});
I have a Razor view in which I want to render the result of another action. So what I tried doing is this
#Html.Action("Index", "Home", new { area = "Portal" })
However this doesn't seem to render anything on the page. But when I check which URL is rendered by the Url.Action with the same parameters it's giving me the proper URL.
#Url.Action("Index", "Home", new { area = "Portal" }) // this shows /Portal/Blog/Index
#Html.Action("Index", "Home", new { area = "Portal" }) // this doesn't show anything
And if I go in my browser to /Portal/Blog/Index I can see content I'm trying to load just fine. I've even tried removing all of the code from HomeController so the action is simply
public ActionResult Index()
{
// also tried returning this.PartialView() but it makes no difference
return this.View();
}
and the Index.cshtml is just
#{
Layout = null;
}
<div>test</div>
I've been looking for a long time for this but I'm still stuck, I need to have an upload control where the user can upload a document and give additional information.
I've had to do this before without the upload control so what I do is I get an ajax.beginform that will give all the input from the user to the controller and than close the popup trough a onsucces function, so this looks like this:
view:
#using (Ajax.BeginForm("Save", "Documents", new AjaxOptions { HttpMethod = "Post", OnSuccess = "CloseDialog" }, new { #class = "form-inline", id = "FormId" }))
{
#Html.Label("Description", "Description")
<div class="span3">
#Html.TextBoxFor(m => m.Description)
</div>
}
I tried adding there an Html.BeginForm but then I found out that it is not possible to use nested forms so I deleted this.
In my controller I have:
public PartialViewResult Index(string description)
{
var model = new DocumentsModel{ Description = description};
return PartialView(model);
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file, string description)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(#"D:\Documentds\"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index", new { description = description });
}
Ofcourse because the html.beginform won't work this controlleraction won't work either
So my question is how to do this without having to use a html.beginform?
You need to have the file upload inside the form and also the enctype="multipart/form-data" property on the form that calls uploadfile. That could be one problem.
Also, you could use JavaScript to submit the form you want from another part of the page without having them nested and keeping your design.
I trying to get my link to open in a new tab (it must be in razor format):
#Reports.RunReport
This is not working though. Anyone know how to do this?
Just use the HtmlHelper ActionLink and set the RouteValues and HtmlAttributes accordingly.
#Html.ActionLink(Reports.RunReport, "RunReport", new { controller = "Performance", reportView = Model.ReportView.ToString() }, new { target = "_blank" })
Looks like you are confusing Html.ActionLink() for Url.Action(). Url.Action has no parameters to set the Target, because it only returns a URL.
Based on your current code, the anchor should probably look like:
<a href="#Url.Action("RunReport", "Performance", new { reportView = Model.ReportView.ToString() })"
type="submit"
id="runReport"
target="_blank"
class="button Secondary">
#Reports.RunReport
</a>
That won't compile since UrlHelper.Action(string,string,object,object) doesn't exist.
UrlHelper.Action will only generate Urls based on the action you provide, not <a> markup. If you want to add an HtmlAttribute (like target="_blank", to open link in new tab) you can either:
Add the target attribute to the <a> element by yourself:
<a href="#Url.Action("RunReport", "Performance",
new { reportView = Model.ReportView.ToString() })",
target = "_blank" type="submit" id="runReport" class="button Secondary">
#Reports.RunReport
</a>
Use Html.ActionLink to generate an <a> markup element:
#Html.ActionLink("Report View", "RunReport", null, new { target = "_blank" })
If your goal is to use the ActionLink helper and open a new tab:
#Html.ActionLink("New tab please", "Home", null , new { target = "_blank" })
#Html.ActionLink("New tab please", "Home", Nothing, New With {Key .target = "_blank"})
#Html.ActionLink(
"Pay Now",
"Add",
"Payment",
new { #id = 1 },htmlAttributes:new { #class="btn btn-success",#target= "_blank" } )
With Named arguments:
#Html.ActionLink(linkText: "TestTab", actionName: "TestAction", controllerName: "TestController", routeValues: null, htmlAttributes: new { target = "_blank"})
For
#Url.Action
Link Text
asp.net mvc ActionLink new tab with angular parameter
<a target="_blank" class="btn" data-ng-href="#Url.Action("RunReport", "Performance")?hotelCode={{hotel.code}}">Select Room</a>
You are setting it't type as submit. That means that browser should post your <form> data to the server.
In fact a tag has no type attribute according to w3schools.
So remote type attribute and it should work for you.
#Reports.RunReport
I am encountering an issue with what should be a simple logon form in ASP.NET MVC 2. Essentially my form looks a little something like this:
using (Html.BeginForm("LogOn", "Account", new { area = "Buyers" }, FormMethod.Post, new { ID = "buyersLogOnForm" }))
I have a RequiresHTTPS filter on the LogOn Action method but when it executes I receive the following message
The requested resource can only be
accessed via SSL
At this point the only solution that worked was to pass in an extra action htmlattribute as follows:
var actionURL = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
using (Html.BeginForm("LogOn", "Account", new { area = "Buyers" }, FormMethod.Post, new { ID = "buyersLogOnForm", #action = actionURL }))
While this works I wonder a) why i am seeing this issue in the first place and b) if there is a more straightforward way of posting to https from a http page?
[Edit]
I should have stated that the logon dropdown will be available on many public pages. I do not want all of my pages to be HTTPS. For instance, my hope page - which ANYONE can see - should not be HTTPS based. Essentially I need to specify the protocol in my form but have no idea how to do that, or if it is possible.
I would appreciate any advice/suggestions.
Thanks in advance
JP
You could use
<form action =" <%= Url.Action(
"action",
"controller",
ViewContext.RouteData.Values,
"https"
) %>" method="post" >
Use the [RequireHttps] attribute on both the action that renders the form and the one you are posting to.
Update: Review the comments below about the security vulnerabilities of this approach before considering the use of this code.
I found that a hybrid of JP and Malcolm's code examples worked.
using (Html.BeginForm("Login", "Account", FormMethod.Post, new { #action = Url.Action("Login","Account",ViewContext.RouteData.Values,"https") }))
Still felt a bit hacky though so I created a custom BeginForm helper. The custom helper is cleaner and does not require https when running locally.
public static MvcForm BeginFormHttps(this HtmlHelper htmlHelper, string actionName, string controllerName)
{
TagBuilder form = new TagBuilder("form");
UrlHelper Url = new UrlHelper(htmlHelper.ViewContext.RequestContext);
//convert to https when deployed
string protocol = htmlHelper.ViewContext.HttpContext.Request.IsLocal == true? "http" : "https";
string formAction = Url.Action(actionName,controllerName,htmlHelper.ViewContext.RouteData.Values,protocol);
form.MergeAttribute("action", formAction);
FormMethod method = FormMethod.Post;
form.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
htmlHelper.ViewContext.Writer.Write(form.ToString(TagRenderMode.StartTag));
MvcForm mvcForm = new MvcForm(htmlHelper.ViewContext);
return mvcForm;
}
Example usage:
#using (Html.BeginFormHttps("Login", "Account"))