i am dynamically create contents and buttons into my code behind "tree.aspx.cs" page
sbmainTbl.AppendFormat("<tr><td><div class=\"a\">{0}<div class=\"details\"<p id=\"p\">{1}</p><ul><li>Parent-UnitId:{2}</li><li>Address :{3}</li><li>City: {4}</li><li>EmailId: {5}</li><li>PhoneNo: {6}</li><li>FaxNo: {7}</li><li><input type=\"button\" value=\"ADD\" onclick=\"f2();\" /></li></ul></div></div></div></td></tr>",
CellText(dtparent.Rows[0]["UnitName"].ToString()),
CellText(dtparent.Rows[0]["UnitName"].ToString()),
CellText(dtparent.Rows[0]["ParentUnitId"].ToString()),
CellText(dtparent.Rows[0]["Address"].ToString()),
CellText(dtparent.Rows[0]["City"].ToString()),
CellText(dtparent.Rows[0]["EmailId"].ToString()),
CellText(dtparent.Rows[0]["PhoneNo"].ToString()),
CellText(dtparent.Rows[0]["FaxNo"].ToString()));
Now i have another page called "Add.aspx Page"
in that page i have textbox
<asp:TextBox ID="txtunitname" runat="server" CssClass="textbox"></asp:TextBox>
now i just want on click on dynamically create button on "tree.aspx" page the "unitname(dynamically create value)" will pass "Add.aspx" page and textbox should fill with unitname.
kindly help me,
Thanks.
To pass pass values using asp.net you need to follow the asp.net way.
First on the first page you place that value on a page control, I prefer on your case a hidden field, that is also post back to any page.
Then you add your value to that field
ValueHiddenField.value = CellText(dtparent.Rows[0]["UnitName"].ToString())
and you make also a public field so the second page can read it
public string ValueHiddenField
{
get
{
return ValueHiddenField.value;
}
}
And you say to the button to post back to the second page using the PostBackUrl field of the button.
Now this is the way you get your data from second page:
On the redirect page declare what is the previous page on aspx as:
<%# Reference Page ="~/PreviousPageName.aspx" %>
and on code behind on second page you get the value as:
if (Page.PreviousPage != null)
{
if (Page.PreviousPage is PreviousPageClassName)
{
Label1.Text = ((PreviousPageClassName)Page.PreviousPage).ValueHiddenField;
}
else
{
Label1.Text = "no value";
}
}
else
Label1.Text = "no value from previous page";
Similar answers:
cross page posting
Cross-page posting. Is it a good pratice to use PreviousPage in Asp.net?
Related
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);
}
I'm working on a project (quite new to this topic) where users can add multiple addresses for one company.
Now I would like to add a partial view to my side (by click on an action link) to have a possibility to enter multiple phone numbers for each of these addresses.
The empty sub partial (for phone and..) should be placed directly after the address where the action link was clicked (inherent div element is placed there)
For example I have two addesses for company xyz I render two actionlinks and for each an pending div element.
How can I tell my ajax action link to update only the coresponding div within a for loop? I mean, if the first link is clicked the partial view should be rendert at the first div elements position and so on. I have an addressId available to add it to the link and the id of the div.
The partial is returned correct by the controller (checked with Fiddler), but it will not be rendert on the page.
If I remove the reference to my "AddressId" in ActionLink's "UpdateTargetId" and in the placeholder div - everything works fine.
If I check webside source code I have the same "names" (ComRow+1) in targetId and div id - see:
... data-ajax="true" data-ajax-mode="after" data-ajax-update="#ComRow+1" href="/companyDetails/GetCommunicationEditor/1">Add a new Phone no./Email for this Address...
and:
</div>
<div id="ComRow+1">
</div>
I found this:
dynamic update target id in Ajax.ActionLink
but it doesn't work in my case (maybe I'm in a for Loop?)
and this:
How to add a Model Primary Key which is INT, to an ActionLink LinkText
but the ".ToString()" does'nt solve the problem
What am I doing wrong? Many thank's in advance
This is the code that generates the loop:
<div>
#for (int i = 0; i < Model.EditorAddresses.Count(); i++)
{
#Html.EditorFor(m => m.EditorAddresses[i])
//Start - render link to add template for the new address
<div>
#Ajax.ActionLink("Add a new Phone no./Email for this Address...",
"GetCommunicationEditor", new { #id = Model.EditorAddresses.ElementAt(i).AddressId },
new AjaxOptions
{
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "ComRow+" + Model.EditorAddresses.ElementAt(i).AddressId.ToString(),
});
</div>
//End - render link to add template for the new address
<div id="ComRow+#Model.EditorAddresses.FirstOrDefault().AddressId.ToString()">
</div>
//<div id="ComRow+<%=Model.EditorAddresses.ElementAt(i).AddressId%>"></div>
...
}
Solved the problem by myself! I removed the string element "ComRow".
I modified the Ajax Actionlink:
UpdateTargetId = Model.EditorAddresses.ElementAt(i).AddressId.ToString(),
The result is: data-ajax-update="#1" (in "view source code" for website)
And I also changed the code of the "div id" to:
id="#Model.EditorAddresses.ElementAt(i).AddressId.ToString()"
With the result:
id="1" if I look at the website source code
P.S. There was also a mistake in the posted code for the div element "...FirstOrDefault().." was wrong. The right way is to use "...ElementAt(i)..".
I think the problem was, that the div id does not accept a "+"
Maybe this helps somebody
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.
I have some regular input webpage where users type in some details about item.
Then after the user presses the submit button she is redirected to a webpage saying that everything went fine. The problem is that if she clicks the back button then the input page is displayed again, and if she hits the sumbit, the form is re-submitted and another item is being written to the database, which is not desirable, of course.
I'm using ASP.NET MVC in C#. What is the best-practice way to deal with this situation?
You can create a hidden form element that marks the form as unique. Each time the form is written by the server, create a new random unique value. When the form is submitted, have the server check that the identifier has not been used before.
The problem is if you want to allow the user to press back and re-submit to create a second entry, there is no way to tell if the user intended to make a second copy or not. What you could do in this situation is make a link which takes the user to the same form, but with a newly generated hidden form element containing the unique identifier.
You can use TempDate and a hidden form value to both store a unique token, and compare them on the postback.
Like this:
public ActionResult FormDemo()
{
var guid = Guid.NewGuid().ToString();
ViewData.Model = guid;
TempData.Add("guid", guid);
return View();
}
[HttpPost]
public ActionResult FormDemo(string name, string guid)
{
if(guid != (string)TempData["guid"]) return new HttpStatusCodeResult(500);
return RedirectToAction("FormDemoReceipt");
}
public ActionResult FormDemoReceipt()
{
return Content("Form submitted OK!");
}
My FormDemo view looks like this:
#using (Html.BeginForm())
{
#Html.Hidden("guid", Model)
#Html.TextBox("name");
<input type="submit"/>
}
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.