render .ascx page into .aspx page using javascript, jquery - asp.net

i have aspx page which has following js function which is called on button click
<input type="button" onclick="calltemp1()" value="Temp1"/>
<script type="text/javascript">
function calltemp1() {
$("#Renderthisdiv").load("/Views/Templates/_Temp1.ascx");
}
</script>
my _Temp1.ascx page renders another page Temp1.ascx
my _Temp1.ascx contains
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>
<%Html.RenderPartial("/Views/Templates/Temp1.ascx"); %>
</div>
when i run the program i get the JavaScript runtime error saying "object expected"
please help me to solve this issue

Your JavaScript call is going to make another trip through the MVC Pipeline. So it will hit routing, a controller, and then a view. Your JavaScript should not try to hit the ascx file directly, but a route that maps to a controller that renders the view.
Your JS should look like this (note this is using a root relative URL, you may have to adjust):
$("#Renderthisdiv").load("/template/temp1");
Alternately, you can use an HTML helper to get the URL, but the JS will have to be in your view:
$("#Renderthisdiv").load("<%= Html.Action("temp1", "template") %>");
That URL will hit the Temp1 action on the TemplateController
public class TemplateController : Controller {
public ViewResult Temp1() {
return View("Temp1");
}
}

Just add the appropriate action to your controller so you can use jQuery to render it:
public class TemplateController : Controller {
public ViewResult Temp1() {
return View("_Temp1")
}
}

Related

How can I change URL string for home page in asp.net mvc 5

In ASP.NET MVC 5 project, I have a page which is home page. This page includes form element which causes GET request like below that.
#using (#Html.BeginForm("Index", "Home", FormMethod.Get))
{
<input name="test" value="deneme" />
<button type="submit">Click me!</button>
}
Controller code is below that;
using System.Web.Mvc;
namespace MyTodoApp.Web.Controllers
{
public class HomeController : MyTodoAppControllerBase
{
public ActionResult Index()
{
return View();
}
}
}
When I click on the submit button, the page go to server with GET method request. But browser URL is changing after this home page request. On other pages doesn't cause this behaviour. Ok, I am understanding because home page is default route page. I don't want to changing URL string for this page with GET method request.
Does anyone have knowledge on this issue?

MVC 4 - Razor - "a potentially dangerous request.form value was detected from the client"

I have an i-Frame on my view that links to an external site. This site takes in some values and some config settings. As part of these config settings is a "CallBackURL". This external website posts to this CallBackUrl.
I specified the CallBackURL to be an action on my control.
View Code
<form id="testForm" method="post" target="testFrame">
<input type="hidden" name="RequestXML" ID="RequestXML" value="<Request><RedirectURL>Account/TokenRequest</RedirectURL></Request>"
</form>
<iframe id="testFrame" name="testFrame" frameborder="0" style="width:1000px;height:500px"></iframe>
Controller Code
[HttpPost]
[ValidateInput(false)]
public ActionResult TokenRequest()
{
if (Request.Form["ResponseXML"] != null)
ViewBag.ResponseXML = Request.Form["ResponseXML"];
return PartialView();
}
inside my controller action I get the following error:"a potentially dangerous request.form value was detected from the client"
I also set this in the webconfig
<httpRuntime requestValidationMode="2.0" />
<pages validateRequest="false"...
What am I doing wrong?
EDIT
I was editing the wrong web.config file. I was adding it to the web.config inside the views folder. Once I changed it to the right place it started working.
The above solution was not working for me in MVC4. What works for me is only to put an attribute above the action. No need to change your web.config or add AllowHtml attribute.
[HttpPost]
[ValidateInput(false)]
public ActionResult TokenRequest(TokenRequestModel model)
{
if (!string.IsNullOrEmpty(model.ResponseXML))
ViewBag.ResponseXML = model.ResponseXML;
// ...
Try using a model instead of just using html control direct. and also use the AllowHtml Attribute.
Model:
public TokenRequestModel
{
[AllowHtml]
public string ResponseXML {get;set;}
}
Action:
[HttpPost]
public ActionResult TokenRequest(TokenRequestModel model)
{
if (!string.IsNullOrEmpty(model.ResponseXML))
ViewBag.ResponseXML = model.ResponseXML;
return PartialView();
}
You can try
[HttpPost]
public ActionResult TokenRequest()
{
if (Request.Unvalidated().Form["ResponseXML"] != null)
ViewBag.ResponseXML = Request.Unvalidated().Form["ResponseXML"];
return PartialView();
}
I think the Unvalidated() will make the error go away without the need to edit webconfig
I tried this and worked for me:
on form submit call a javascript function that saves in an hiddenfield the value encoded using 'encodeURIComponent'.
Then in the same function clear the value of the textbox with the dangerous value. In this way the form will submit just the encoded value.
<input type="submit" value="Save" class="btn btn-danger" onclick="encodeLabel1()" />
<script>
function encodeLabel1() {
var label = $('#txt').val();
$('#hfLabel1Encoded').val(encodeURIComponent(label));
$('#txt').val('');
}
</script>
This is a workaround but it works and the validation is still active.

Calling an ASPX method from an ASCX control

I have a method HasAdminRole() on home.aspx that I call from an ASCX control. And the ASCX works using (Home)this.Page).HasAdminRole() with the user control on home.aspx
Now, when I add that same ASCX to a different ASPX page Adminuser.aspx, I get an error when the ASCX tries to call (Home)this.Page).HasAdminRole() from a different ASPX page than when on home.aspx
I get the error Unable to cast object of type 'ASP.adminuser_aspx' to type 'CALE.Home'.
How do I resolve this when using the same ASCX on multiple ASPX's and the user control tries to call the single method on Home.aspx
Suggest moving your admin/roles logic out from your .aspx and into a class that's accessible from both your .aspx and .ascx. It's a bit of 'separation of concerns' and a bit of tidiness in having the logic in common areas. Basically -- only keep page related logic in your page code-behind.
public static class Roles
{
public static HasAdminRole(User someUser)
{
// implementation
}
}
Call it from any page's code-behind or other helper class:
User foo;
bool isAdmin = Roles.HasAdminRole(foo);
So I just figured out a solution to this problem.
You can create a client side trigger in the aspx page and call it with javascript from your ascx page.
e.g.
aspx page:
<script>
function doSomething()
{
//set hidden field values or do whatever else you might need to do here
$('#<%= btnDoSomething.ClientID%>').click();
}
</script>
<asp:Button runat="server" ID="btnDoSomething" OnClick="btnDoSomething_Click" CssClass="hidden" />
aspx code behind:
protected void btnDoSomething_Click(object sender, EventArgs e)
{
//do whatever you need to on the aspx page
}
Now you can call that javascript function from any ascx page that you like.
e.g.
ascx page:
<button type="button" onclick="doSomething()">do something on your aspx page<button/>

Rendering view in ASP.Net MVC

In my code I am using a partial view (call it PV1)
<div id="div_1">
<% Html.Partial("PV1", Model); %>
</div>
and in that partial view I am using "Ajax.BeginForm" to redirect it to a particular action, hence it is doing so ...
using (Ajax.BeginForm("action1", "Forms", null, new AjaxOptions { UpdateTargetId = "div_1" }, new { id = "form1" }))
{
Response.write("I am here.");
}
public ActionResult action1(XYZ Model)
{
//
return PartialView("PV1", Model);
}
at the last line of action I am again calling the same partial 'PV1', hence it is doing this too ...
but when rendering the view it don't print or do the steps written with in partial view, it override them with and show nothing ...
Html.Partial actually returns the result of rendering the view, you want to do <%= Html.Partial() %> or <% Html.RenderPartial(); %>
Html.Partial() returns the Html and thusly must be output on the page via <%= %> and Html.RenderPartial() uses Response.Write to output onto the page and can be used with <% %>.
This is not what you would use Ajax.BeginForm for. That helper is used to create actual <form> tags that will later be submitted to the server using MVC's unobtrusive ajax (so you still need some kind of a trigger action - a button, javascript - anything that submits the form).
I'm am not very clear on what you're trying to achieve. If you want to load a partial view with ajax, I would suggest using something like jQuery's ajax load method.

Pagemethods in asp.net

My Pagemethod implementation is not working in Chrome browser.
I have ASP.NET 3.5 web application developed in VS 2008.
The code below not working in chrome or Safari:
function FetchDataOnTabChange(ucName)
{
PageMethods.FetchData(ucName, OnSuccessFetchDataOnTabChange, OnErrorFetchDataOnTabChange);
}
function OnErrorFetchDataOnTabChange(error)
{
//Do something
}
function OnSuccessFetchDataOnTabChange(result)
{
//Do something
}
This should work in all browsers by following the steps below:
The page method must have the
System.Web.Services.WebMethod
attribute. [WebMethod]
The page method must be public.
[WebMethod] public ...
The page method must be static.
[WebMethod] public static ...
The page method must be defined on
the page (either inline or in the
code-behind). It cannot be defined
in a control, master page, or base
page.
The ASP.NET AJAX Script Manager must
have EnablePageMethods set to true.
This is from a working application
aspx page:
/* the script manager could also be in a master page with no issues */
<asp:ScriptManager ID="smMain" runat="server" EnablePageMethods="true" />
<script type="text/javascript">
function GetDetails(Id) {
PageMethods.GetDetails(doorId);
}
</script>
code behind:
[System.Web.Services.WebMethod]
public static void GetDetails(string Id)
{
}

Resources