I'm trying to create a ResetPassword Page and I need to create something like that!
myApi.azure.com/ResetPassword?hash=YYYYYYYYYYYYYY
I already know how to create a link to another controller, but that way it would trigger the Action just with the click, and what I need is pass the hash as parameter inside of that URL and them, call a controller!
var link = new Uri(Url.Link("ValidationEmailUser", new { Code = emailToken }));
Something like this:
public IHttpActionResult RedirectAction()
{
var urlFormat = string.Format("https://www3.olx.com.br/account/forgotten_password/?hash={0}", emailToken);
var location = new Uri(urlFormat);
return this.Redirect(location);
}
Related
I have a view that needs to load different component vieww dynamically based on component view name. I am using a function in C# to achieve this:
public ViewComponentResult GetComponentView(string componentName, int id)
{
return ViewComponent(componentName, new { id = id });
}
This is in a controller CT40. So the file structure is:
/Controllers/CT40/CT40Controller
/Views/CT40/Components/Maintenance/Default.cshtml
/Views/CT40/Components/Maintenance/MaintenanceViewComponents.cs
Inside MaintenanceViewComponents.cs I have:
[ViewComponent(Name = "Maintenance")]
It works find when I call the GetComponentView function with "Maintenance" as the component name.
But I want to move the GetComponentView function to the HomeController. When I do this, it returns
"System.InvalidOperationException: The view 'Components/Maintenance/Default'"
I have tried every path I can think of, same thing:
/CT04000/Maintenance
/CT04000/Components/Maintenance
/CT04000/Components/Maintenance/Default.cshtml
Views/CT04000/Components/Maintenance/Default.cshtml
Same error every time.
Any idea what path I need to put in to get Homecontroller to look in:
/Views/CT40/Components/Maintenance?
I was looking at the problem in the wrong place.
I was trying to put the path to the view in componentName here:
public ViewComponentResult GetComponentView(string componentName, int id)
{
return ViewComponent(**componentName**, new { id = id });
}
But the path needed to go in statement
return View(path, model);
in the file MaintenanceViewComponents.cs.
I added the path "~/Views/CT04000/Components/Maintenance/Default.cshtml" and worked liked charm.
I'm using ASP.Net MVC 5, and I want to pass data from the controller to the view WITHOUT adding it to the URL.
I've tried it like this:
public ActionResult Index(LoginViewModel loginViewModel)
{
var landingPgVm = new LandingPgViewModel();
landingPgVm.ElectionName = loginViewModel.ElectionName;
landingPgVm.LandingPageTitle = loginViewModel.LandingPageTitle;
landingPgVm.LandingPageMessage = loginViewModel.LandingPageMessage;
return View("Landing", landingPgVm);
}
And this:
public ActionResult Index(LoginViewModel loginViewModel)
{
var landingPgVm = new LandingPgViewModel();
landingPgVm.ElectionName = loginViewModel.ElectionName;
landingPgVm.LandingPageTitle = loginViewModel.LandingPageTitle;
landingPgVm.LandingPageMessage = loginViewModel.LandingPageMessage;
ViewData["lpvm"] = landingPgVm;
return View("Landing");
}
And still, I get this:
http://localhost:nnnnn/Landing?VotingIsOpen=False&UserIp=%3A%3A1&BrowserAgent=Mozilla%2F5.0%20%28Windows%20NT%2010.0%3B%20Win64%3B%20x64%29%20AppleWebKit%2F537.36%20%28KHTML%2C%20like%20Gecko%29%20Chrome%2F73.0.3683.103%20Safari%2F537.36&ElectionId=1&LoginId=********&LoginPin=*********&ElectionName=2019%20Member-at-Large%20Board%20Election&LandingPageTitle=Success%21&LandingPageMessage=Landing%20Page%20MESSAGE
So sorry that I let my frustration at, what turned out to be MYSELF, spill over onto these pages.
It's been some time since I've done a 'standard' MVC site and forgot how the logic is supposed to flow. (Sometimes it takes getting all the way to posting to SO before I finally figure out/realize the error(s) of my way(s)).
Thanks to info found on the MS docs site here (https://learn.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset), namely, the POST method example under the "You must also update the HttpPost Login action method:" text, I've got it figured out.
I'm trying to make a targetingIdeaService API call to Google AdWords. This is my code so far:
[HttpGet]
public IEnumerable<string> Get()
{
var user = new AdWordsUser();
using (TargetingIdeaService targetingIdeaService = (TargetingIdeaService)user.GetService(AdWordsService.v201802.TargetingIdeaService))
{
// Create selector.
TargetingIdeaSelector selector = new TargetingIdeaSelector();
selector.requestType = RequestType.IDEAS;
selector.ideaType = IdeaType.KEYWORD;
selector.requestedAttributeTypes = new AttributeType[] {
AttributeType.KEYWORD_TEXT,
AttributeType.SEARCH_VOLUME,
AttributeType.AVERAGE_CPC,
AttributeType.COMPETITION,
AttributeType.CATEGORY_PRODUCTS_AND_SERVICES
};
// Set selector paging (required for targeting idea service).
var paging = Paging.Default;
// Create related to query search parameter.
var relatedToQuerySearchParameter =
new RelatedToQuerySearchParameter
{ queries = new String[] { "bakery", "pastries", "birthday cake" } };
var searchParameters = new List<SearchParameter> { relatedToQuerySearchParameter };
var page = new TargetingIdeaPage();
page = targetingIdeaService.get(selector);
return new string[] { "value1", "value2" };
}
}
it looks ok, compiles at last, and so on. But then I went into debug mode. And I saw this:
So as you can see, the variable doesn't have the access token. The other data comes from app.config file.
I am quite certain the keys passed in are correct.
Then the code throws the famous invalid_grand error. In my case, I believe that's because the access token is not being generated. I'm new to AdWords and ASP.NET, so I probably missed something, but I have no idea what.
I used the
docs,
Code Structure instructions, and
code examples to put it all together.
I had my configuration wrong. I had to recreate all the credentials using incognito window. If you have any issues just open a thread here: https://groups.google.com/forum/#!forum/adwords-api
In a view of ClimateChartController I do this code:
#Html.ActionLink("Kies land", "ListCountries", "Continent" new {Selectedyear = #ViewBag.SchoolYear, continentId = #ViewBag.ContinentId})
So this should go to the method ListCountries of ContinentController, along with the given parameters.
Now this doesn't work, if I do it without the parameters it goes to the method but well, I need the parameters...
For now I resolved this by using the following method in ClimateChartController:
public ActionResult ListCountries(int selectedyear, int continentid)
{
return RedirectToAction("ListCountries", "Continent",
new { selectedYear = selectedyear, continentId = continentid });
}
This works as intended, but causes cluttering of code and isn't neat.
So how can I call a method of another controller and pass some parameters with it?
Try this:
#Html.ActionLink("Kies land", "ListCountries", "Continent" , null, new {Selectedyear = #ViewBag.SchoolYear, continentId = #ViewBag.ContinentId})
OR:
Html.ActionLink("Kies land", "ListCountries", "Continent", new {Selectedyear = #ViewBag.SchoolYear, continentId = #ViewBag.ContinentId}, null)
There are possible solutions here:
Why does Html.ActionLink render "?Length=4"
First, some context:
Language - C#
Platform - .Net Framework 4.5
Project type - ASP.Net MVC 4
I am trying to determine which View in an MVC project is handling an explicit call to the following method. The MSDN docs for the method are here: http://msdn.microsoft.com/EN-US/library/dd492930.aspx
protected internal ViewResult View(
Object model
)
The original Author is using a View to generate a PDF file with a third-party library. I need to modify the view to include additional information.
The problem: I'm having trouble finding which View to modify. There are hundreds of them, and (IMHO) they are poorly named and organized. The basic process for generating a PDF looks like this. I'm getting confused in between steps 3 and 4.
An Entity's ID is passed to an ActionResult
The Entity is retrieved from the backing store
The model is passed to the Controller.View method mentioned above:
var viewModel = View(model);
var xmlText = RenderActionResultToString(viewModel);
The resulting ViewResult is used with an instance of ControllerContext to generate HTML as if being requested by a browser.
The resulting HTML is passed to the third-party tool and converted to a PDF.
I understand everything else very clearly. What I don't understand is how the call to View(model) determines which View file to use when returning the ViewResult. Any help greatly appreciated!
I'm including the code below, in case it helps anybody determine the answer.
The ActionResult:
public ActionResult ProposalPDF(String id, String location, bool hidePrices = false)
{
var proposal = _adc.Proposal.GetByKey(int.Parse(id));
var opportunity = _adc.Opportunity.GetByKey(proposal.FkOpportunityId.Value);
ViewData["AccountId"] = opportunity.FkAccountId;
ViewData["AccountType"] = opportunity.FkAccount.FkAccountTypeId;
ViewData["Location"] = location;
ViewData["HidePrices"] = hidePrices;
return ViewPdf(proposal);
}
The ViewPDF method:
protected ActionResult ViewPdf(object model)
{
// Create the iTextSharp document.
var document = new Document(PageSize.LETTER);
// Set the document to write to memory.
var memoryStream = new MemoryStream();
var pdfWriter = PdfWriter.GetInstance(document, memoryStream);
pdfWriter.CloseStream = false;
document.Open();
// Render the view xml to a string, then parse that string into an XML dom.
var viewModel = View(model);
var xmlText = RenderActionResultToString(viewModel);
var htmlPipelineContext = new HtmlPipelineContext();
htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
//CSS stuff
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
var cssResolverPipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(document, pdfWriter)));
var xmlWorker = new XMLWorker(cssResolverPipeline, true);
var xmlParser = new XMLParser(xmlWorker);
xmlParser.Parse(new StringReader(xmlText));
// Close and get the resulted binary data.
document.Close();
var buffer = new byte[memoryStream.Position];
memoryStream.Position = 0;
memoryStream.Read(buffer, 0, buffer.Length);
// Send the binary data to the browser.
return new BinaryContentResult(buffer, "application/pdf");
}
The RenderActionResultToString helper method:
protected string RenderActionResultToString(ActionResult result)
{
// Create memory writer.
var sb = new StringBuilder();
var memWriter = new StringWriter(sb);
// Create fake http context to render the view.
var fakeResponse = new HttpResponse(memWriter);
var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request, fakeResponse);
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), this.ControllerContext.RouteData, this.ControllerContext.Controller);
var oldContext = System.Web.HttpContext.Current;
System.Web.HttpContext.Current = fakeContext;
// Render the view.
result.ExecuteResult(fakeControllerContext);
// Restore data.
System.Web.HttpContext.Current = oldContext;
// Flush memory and return output.
memWriter.Flush();
return sb.ToString();
}
I'm not exactly sure what you're asking, but, when you call View(model) the view that is chosen is based upon conventions.
Here is an example:
public class HerbController : Controller {
public ActionResult Cilantro(SomeType model) {
return View(model)
}
}
That will look for a view file called Cilantro.cshtml in a folder called Herb (Views/Herb/Cilantro.cshtml). The framework will also look in the Shared directory as well in case it is a view that is meant to be shared across multiple results.
However, you may also want to look at the Global.asax file to see if there are any custom view paths being setup for the view engine. The example I gave above is based upon the default conventions of ASP.NET MVC. You can override them to meet your needs better if needed.
The convention for views is that they are in a folder named after the controller (without "Controller") and the .cshtml file inside that folder is named after the calling action. In your case, that should be:
~/Views/[Controller]/ProposalPdf.cshtml
The logic to determine which view template will be used is in the ViewResult that is returned from the call
var viewModel = View(model);
And how the view is selected is determined by the configured ViewEngine(s), but it will use the current Area, Controller and Action route values to determine what view should be served.
What the route values are for the ProposalPDF action will depend on how your routing is configured, but assuming the defaults, the action route value will be ProposalPDF, the controller route value will be the name of the controller class in which this action resides (minus the Controller suffix) and the area will be the area folder in which the controller lives, with a value of empty string if in the default controller folder. Then using these route values, a view will be looked up in the Views folder using the following convention
~/Views/{Area}/{Controller}/{View}.cshtml
There is always Glimpse that can help with providing runtime Diagnostics too, such as which View file was used to serve up the returned page, although I'm not sure how this would look when a ViewResult is executed internally to provide the contents of a file.