call code behind functions with html controls - html

I have a simple function that I want to call in the code behind file name Move
and I was trying to see how this can be done and Im not using asp image button because not trying to use asp server side controls since they tend not to work well with ASP.net MVC..the way it is set up now it will look for a javascript function named Move but I want it to call a function named move in code behind of the same view
<img alt='move' id="Move" src="/Content/img/hPrevious.png" onclick="Move()"/>
protected void Move(){
}
//based on Search criteria update a new table
protected void Search(object sender EventArgs e)
{
for (int i = 0; i < data.Count; i++){
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell CheckCell = new HtmlTableCell();
HtmlTableCell firstCell = new HtmlTableCell();
HtmlTableCell SecondCell = new HtmlTableCell();
CheckBox Check = new CheckBox();
Check.ID = data[i].ID;
CheckCell.Controls.Add(Check);
lbl1.Text = data[i].Date;
lbl2.Text = data[i].Name;
row.Cells.Add(CheckCell);
row.Cells.Add(firstCell);
row.Cells.Add(SecondCell);
Table.Rows.Add(row);
}
}

Scott Guthrie has a very good example on how to do this using routing rules.
This would give you the ability to have the user navigate to a URL in the format /Search/[Query]/[PageNumber] like http://site/Search/Hippopotamus/3 and it would show page 3 of the search results for hippopotamus.
Then in your view just make the next button point to "http://site/Search/Hippopotamus/4", no javascript required.
Of course if you wanted to use javascript you could do something like this:
function Move() {
var href = 'http://blah/Search/Hippopotamus/2';
var slashPos = href.lastIndexOf('/');
var page = parseInt(href.substring(slashPos + 1, href.length));
href = href.substring(0, slashPos + 1);
window.location = href + (++page);
}
But that is much more convoluted than just incrementing the page number parameter in the controller and setting the URL of the next button.

You cannot do postbacks or call anything in a view from JavaScript in an ASP.NET MVC application. Anything you want to call from JavaScript must be an action on a controller. It's hard to say more without having more details about what you're trying to do, but if you want to call some method "Move" in your web application from JavaScript, then "Move" must be an action on a controller.
Based on comments, I'm going to update this answer with a more complete description of how you might implement what I understand as the problem described in the question. However, there's quite a bit of information missing from the question so I'm speculating here. Hopefully, the general idea will get through, even if some of the details do not match TStamper's exact code.
Let's start with a Controller action:
public ActionResult ShowMyPage();
{
return View();
}
Now I know that I want to re-display this page, and do so using an argument passed from a JavaScript function in the page. Since I'll be displaying the same page again, I'll just alter the action to take an argument. String arguments are nullable, so I can continue to do the initial display of the page as I always have, without having to worry about specifying some kind of default value for the argument. Here's the new version:
public ActionResult ShowMyPage(string searchQuery);
{
ViewData["SearchQuery"] = searchQuery;
return View();
}
Now I need to call this page again in JavaScript. So I use the same URL I used to display the page initially, but I append a query string parameter with the table name:
http://example.com/MyControllerName/ShowMyPage?searchQuery=tableName
Finally, in my aspx I can call a code behind function, passing the searchQuery from the view data. Once again, I have strong reservations about using code behind in an MVC application, but this will work.
How to call a code-behind function in aspx:
<% Search(ViewData["searchQuery"]); %>
I've changed the arguments. Since you're not handling an event (with a few exceptions, such as Page_Load, there aren't any in MVC), the Search function doesn't need the signature of an event handler. But I did add the "tablename" argument so that you can pass that from the aspx.
Once more, I'll express my reservations about doing this in code behind. It strikes me that you are trying to use standard ASP.NET techniques inside of the MVC framework, when MVC works differently. I'd strongly suggest going through the MVC tutorials to see examples of more standard ways of doing this sort of thing.

Related

How Do I Dynamically Add onclick on a Razor page?

I am iterating through a LARGE list of objects all of which will open the same modal window that will be loaded with dynamic information. To make this work, I create a counter called MenuCounter that I know increments just fine.
That said, I am attempting to wrap a hyperlink around the icons I need to use and the injection of the method keeps pointing to the last value of the MenuCounter.
I first tried this:
...
When I ran into the issue, I tried reducing the code to the following but then the page somehow activates the hyperlink and the modal window appears and will not go away.
...
Can somebody please help me out?
Thank you!
You should apply a lambda expression to the Blazor #onclick directive instead of using the onclick Html attribute, in which case it should call a JS function, which you did not mean.
Note that I've introduced a new directive to prevent the default action of the anchor element: #onclick:preventDefault
Test this code:
#page "/"
<a href="#" #onclick:preventDefault #onclick="#(() => SetupChangeName(MenuCounter))" >Click me...</a>
<div>Counter is #output</div>
#code
{
private int MenuCounter = 10;
private int output;
private void SetupChangeName (int counter)
{
output = counter;
}
}
Note: If you use a for loop to render a list of anchor elements, you must define a variable local to the loop, and provide it as the input to your lambda expression, something like this:
#for(int MenuCounter = 0; MenuCounter < 10; MenuCounter++)
{
int local= MenuCounter;
<a href="#" #onclick:preventDefault #onclick="#(() =>
SetupChangeName(local))" >Click me...</a>
}
otherwise, all the lambda expressions will have the the same value for MenuCounter, which is the value incremented for the last iteration. See For loop not returning expected value - C# - Blazor explaining the issue.
I'm not a fan of onclick attributes, but if you're set on this method, I believe you just need to santize the C# and JS in the same line like this:
...
Adding the quotes will ensure at least an empty string is present for JS, and then you can process it.
Alternative method
Since mixing languages like that is quite frustrating, I find it easier to use data tags, for example
...
And then in your JS file:
var links = document.querySelectorAll('[data-menu-counter]');
links.forEach(x => x.addEventListener('click', /* your function code here */);

Add #id suffix to RedirectToAction() in controller ASP NET MVC

Somehow I find this hard to describe, but here I go:
I have a div in my SelectClasses Razor view page with an id="id152".
In order for me to show that div on the page at reload, I have to add the suffix #id152 to my page url.
<div id="id152">blabla</div>
...
..
Section 7
Now my question: Is there a way to add/pass this suffix to a 'RedirectToAction()'?
public ActionResult Index()
{
//All we want to do is redirect to the class selection page and add a suffix
return RedirectToAction("SelectClasses", "Registration", new { id = 99 })); //add suffix here somewhere
}
So when my SelectClasses view is shown, the url looks something like this:
'[url]/SelectClasses/99#id152'
The RedirectToActionResult (among the rest of RedirectTo* results) is meant to be used for generation of URLs based on registered routing data.
In your case, you wish to concatenate a hash parameter value (#id152) that is not being sent to the server and only used by the browser. That's why said methods don't bother dealing with it.
I suggest you do this instead:
var redirUrl = Url.Action("SelectClasses", "Registration", new { id = 99 });
redirUrl = String.Concat(redirUrl, "#id152");
return Redirect(redirUrl);

Get Route Values in Razor Pages

I want to know how can I get the route values in Razor Pages (Page.cshtml).
Ex.
https://localhost:44320/AdminPanel/Admins
if I was using MVC i would get these datas as
var controller = ViewContext.RouteData.Values["Controller"]; //AdminPanel
var action = ViewContext.RouteData.Values["Action"]; //Admins
How can i get these values in Razor Pages?
For anyone trying to get it you can get it by:
var fullRoute = ViewContext.RouteData.Values["Page"]; // AdminPanel/Admin
Assuming you have a page named AdminPanel.cshtml in your Pages folder, add a parameter after #page on the first line, like this:
#page "{action}"
Then in the code behind (AdminPanel.cshtml.cs), add a prop and a parameter to your OnGet method like so:
private string _action;
public void OnGet(string action) {
_action = action; //now do whatever you want with it
}
You can add a getter if you want to access it in your model back on the cshtml page.
Note: doing the above will make that page require an action be specified. Alternatively, you can also make it optional by adding a question mark (#page "{action?}") and setting a default value in your OnGet (OnGet(string action="")).

Can't find HTML tags in code behind under impersonation

I have an aspx page that inherits the IHttpHandler class.
On page load I issued a call to an Impersonation class in which it renders the content under a different username than that currently logged in. But the problem is when impersonated I call a function back on the code behind in the aspx page that needs to access a div tag in order to insert content to it via an object tag and it doesn't find the tag anymore. Any clue as to why? Or to how am I able to build tags from the code behind in such a situation?
The impersonation function I used is based off of : https://www.codeproject.com/Articles/107940/Back-to-Basic-ASP-NET-Runtime-Impersonation.aspx
And this is the function that is called when impersonated within my aspx page:
public void FUNCTION() //This is called from the impersonation function above
{
report = Session[Document];
string url = "http://localhost/PATH" + report.toString();
HtmlGenericControl objReport = new HtmlGenericControl();
objReport.TagName = "object";
objReport.Attributes.Add("data", url);
Control cntrl = Page.FindControl("objReportFrame");
if (cntrl != null)
cntrl.Controls.Add(objReport);
}

Route values could not taking to the values

I want to route from one page to another page.
Candidatesvas- controller
Here I have code,
[Authorize, HttpPost,HandleErrorWithAjaxFilter]
public ActionResult Details(FormCollection collection)
{
Order order = _repository.GetOrder(LoggedInOrder.Id);
order.CreateDate = DateTime.Now;
order.Amount = 360;
order.Validity = 60;
_repository.Save();
}
when I click Index page,"any link", it saves in db and go to next details page.
Index.aspx:
<%:Html.actionlink("Details","Details","Candidatesvas")%>
like that...
Global.ascx:
routes.MapRouteLowercase(
"SaveVas",
"details/candidatesvas",
new { controller = "Candidatesvas", action = "Details" }
);
But when i click link, it shows "resource cannot be found". i changed many way. please help me. i can't find out the issue?
Your controller action is decorated with the [HttPost] attribute which means that this action is only accessible with the POST verb. Then you have shown some link on your page:
<%:Html.ActionLink("Details","Details","Candidatesvas")%>
But as you know a link sends GET request. If you want to be able to invoke this action you should either remove the [HttpPost] attribute from it or use an HTML <form> instead of a link.
try this
<%:Html.actionlink("Details","Details","Candidatesvas",null,null)%>
You can't use Html.actionlink for post method.
go for jquery
Or call form submit on click function.