passing parameters to .aspx page using renderpartial - asp.net

in my index.aspx page i want to render another module.aspx page using renderpartial
which then render a .htm file
depanding on which parameter is passed from index.aspx (it would be number ie 1,2 etc ,so as to call different different .htm file everytime depending on the parameter)
1).
now i want Index.aspx page to render module.aspx and pass it a parameter(1,2,3,etc)
[the parameters would be passed programatically (hardcoded)]
and
2).
mudule.aspx should catch the parameter and depending on it will call .htm file
my index.aspx has
<% ViewData["TemplateId"] = 1; %>
<% Html.RenderPartial("/Views/Templates/MyModule.aspx", ViewData["TemplateId"]); %>
and module.aspx contains
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<script type="text/javascript" src="/Scripts/jquery-1.3.2.js"></script>
<script type="text/javascript" src="/Scripts/Service.js"></script>
<script type="text/javascript">
debugger;
var tid = '<%=ViewData["TemplateId"] %>';
$.get("/Templates/Select/" + tid, function(result) {
$("#datashow").html(result);
});
</script>
<div id="datashow"></div>
this is my controller which is called by $.get(....) (see code)
public ActionResult Select(int id)
{
return File("/Views/Templates/HTML_Temp" +id.ToString()+".htm" , "text/html");
}
and finally
my .htm file
<div id="divdata" class="sys-template">
<p>Event Title:<input id="title" size="150" type="text"
style="background-color:yellow;font-size:25px;width: 637px;"
readonly="readonly" value="{{title}}" />
</p>
<p>Event Description:<input type="text" id="description" value="{{ description }}"
readonly="readonly" style="width: 312px" /></p>
<p>Event Date: <input type="text" id="date" value="{{ date }}" readonly="readonly"
style="width: 251px"/></p>
<p>Keywords : <input type="text" id="keywords" value="{{keywords}}" readonly="readonly" /></p>
</div>
<script type="text/javascript">
Sys.Application.add_init(appInit);
function appInit() {
start();
}
</script>
start() is javascript method which is in file Service.js
when i run this programm it gives me error
js runtime error: 'object expected'
and debugger highlighted on
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/**xhtml**1-strict.dtd">
pls help me solve the problem

Use like this <% Html.RenderPartial("/Views/Templates/MyModule.ascx", Model); %> for passing the values using Model to a partial view MyModule.ascx. You can also use the method Html.RenderAction

When you use RenderPartial, you are by default passing the Model of your Index.aspx. Your partial view can then be of the same type. You can then use Model.MyParameter to find out which htm file you should be rendering. Otherwise you can pass it in the object parameter of the RenderPartial, and query that object inside of your partial view.

Related

How to Send Post request in java with javax.portlet.ActionResponse.sendRedirect method?

I want to POST to URL but following making it as GET , so How can I POST the
Object portletResponse = webAppAccess.getHttpServletRequest()
.getAttribute(Constants.PORTLET_RESPONSE);
if (portletResponse instanceof javax.portlet.ActionResponse) {
javax.portlet.ActionResponse actionResponse = (javax.portlet.ActionResponse) portletResponse;
actionResponse.sendRedirect(URL);
}
Have you tried to use RequestDispater instead of response.sendRedirect?
It retains the original request, without changing it.
So, it will remain POST if it was POST.
I have done this by using FORM POST method as follows.
webAppAccess.processPage("importedPage");
Added this imported Page in model :
<HTML>
<HEAD>
<title>New Page</title>
</HEAD>
<Body onload="">
<form id="FormID" method="POST" action="actionURL">
<input type="hidden" name="id" id="ID" value="<%=webAppAccess.getVariables().getString("ID")%>"/>
<noscript>
<p>Your browser does not support JavaScript or it is disabled.
Please click the button below to process the request.
</p>
<input type="submit" value="Proceed " name ="submit"></input>
</noscript>
<script>
document.getElementById('FormID').submit();
</script>
</form>
and then MVC controller mapping as follows:
#RequestMapping(value = {"/Details"}, method = RequestMethod.POST)
public String mthDetails(final Model p_model, #RequestParam(value = "id", required = false) final String p_ID){
//code for further logic using ID
}

ASP.NET MVC - prevent submit of invalid form using jQuery unobtrusive validation

I have an ASP.NET project that automatically wires up client side validation using jQuery.Validate and the unobtrusive wrapper built by ASP.NET.
a) I definitely have the appropriate libraries: jquery.js, jquery.validate.js, & jquery.validate.unobtrusive.js
b) And the MVC rendering engine is definitely turned on (ClientValidationEnabled & UnobtrusiveJavaScriptEnabled in the appSettings section of the web.config)
Here's a trivial example where things are broken:
Model:
public class Person
{
[Required]
public string Name { get; set; }
}
Controller:
public ActionResult Edit()
{
Person p = new Person();
return View(p);
}
View:
#model validation.Models.Person
#using (Html.BeginForm()) {
#Html.ValidationSummary(false)
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
}
This generates the following client side markup:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js"></script>
<form action="/Person" method="post">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
<label for="Name">Name</label>
<input data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />
<input type="submit" value="Save" />
</form>
When run it will perform the client side validation, noting that some form elements are invalid, but then also post back to the server.
Why is it not preventing postback on a form with an invalid state?
The Problem
It turns out this happens when you don't include a #Html.ValidationMessageFor placeholder for a given form element.
Here's a deeper dive into where the problem occurs:
When a form submits, jquery.validate.js will call the following methods:
validate: function( options ) {
form: function() {
showErrors: function(errors) {
defaultShowErrors: function() {
showLabel: function(element, message) {
this.settings.errorPlacement(label, $(element) )
Where errorPlacement will call this method in jquery.validate.unobtrusive.js:
function onError(error, inputElement) {
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
When we don't add a placeholder for the validation message, $(this).find(...) won't find anything.
Meaning container.attr("data-valmsg-replace") will return undefined
This poses a problem is when we try to call $.parseJSON on an undefined value. If an error is thrown (and not caught), JavaScript will stop dead in its tracks and never reach the final line of code in the original method (return false) which prevents the form from submitting.
The Solution
Upgrade jQuery Validate Unobtrusive
Newer versions of jQuery Validate handle this better and check for nulls before passing them to $.parseJSON
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
Add ValidationMessageFor
To address the core problem, for every input on your form, make sure to include:
#Html.ValidationMessageFor(model => model.Name)
Which will render the following client side markup
<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js"></script>
<form action="/Person" method="post">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
<label for="Name">Name</label>
<input data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
<input type="submit" value="Save" />
</form>

ajax in asp.net mvc 2

I am using the microsoft ajax and the ajax form looks like this
<% using (Ajax.BeginForm("UserListing", new AjaxOptions
{
UpdateTargetId = "results",
OnComplete = "getData"
}))
{%>
<input id="Submit1" type="submit" value="submit" />
<%} %>
Now, i get the getData() js function called upon completion of the ajax request. all i want is that i need to access the response data of this ajax request inside this function and prevent that data being directed to the div with id results.
Thats because i am returning json result from the controller's action method and i need to parse it and display in the div.
script function is :
<script type="text/javascript">
function getData() {
alert("Response is : ");
}
</script>
the div tag is :
<div id="results">
</div>
I do not want to use other than microsoft ajax. kindly suggest me accordingly.
You could try rendering the response of the ajax request in a partial view containing only hidden fields. Then in your js function you can access the hidden fields using jQuery selectors.
So your action would look something like
[HttpPost]
public ActionResult UserListing()
{
List<string> data = GetUserListing();
return PartialView(data);
}
Your partial view will then only contain hidden fields that you render something like:
<% for (int i = 0; i < Model.Count(); i++)
{ %>
<input id="<%: "User" + i.ToString() %>" type="hidden" value="<%: Model[i] %>" />
<% } %>
That will render as:
<input id="User0" type="hidden" value="PeterSmith" />
Then in your javaScript function you can access each of the fields by doing something like:
function getData() {
var user = $('#User0').val();
alert(user);
}
That will show you the first field rendered. But you can enhance it a bit by looping through all the injected input fields.
Corrected this problem by myself as explained above. need some json parsers, currently looking for those..

Using webform user control on webform in MVC Project

I am using a server control on a single web.forms page. I have to use this control on a web.forms page since its a server control, although this is actually a MVC project. So I created a web.forms folder and put my new page in it. I then copy the example code from the signature control. I get the following error:
The base class includes the field 'ctrlSign', but its type (WebSignatureCapture.SignatureControl) is not compatible with the type of control (ASP.signaturecapture_signaturecontrol_ctlsignature_ascx).
I know the code works because if I removed the ID attribute from the server control, it no longer gives me this error and my control renders. But I need the attribute for the ID so I can perform is post event... Any ideas why?
I am using this signature control. Here's the web.forms code...
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="KahunaCentralTIDRevamp.SignatureCapture.Index" %>
<%# Reference Control="~/SignatureCapture/SignatureControl/ctlSignature.ascx" %>
<%# Register TagPrefix="uc" TagName="Signature" Src="~/SignatureCapture/SignatureControl/ctlSignature.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>Signature Application Demo</title>
</head>
<body>
<form id="frmOrder" method="post" runat="server">
<div>
Please Sign Below:
</div>
<div>
<uc:Signature ID="ctrlSign" SignHeight="150" SignWidth="300" SignatureCodePath="~/SignatureCapture/SignatureControl/"
SavePath="~/SignatureCapture/" SignatureFileFormat="Gif" runat="server" />
<%-- <uc:Signature id="ctlMySignature" PenColor="Red" PenWidth="2" BackColor="Yellow" SignWidth="300" SignHeight="150"
SavePath="~/Signatures/" SignatureCodePath="~/SignatureControl/" SignatureFileFormat="Gif" Runat="server"></uc:Signature>--%>
</div>
<div>
<input type="button" value=" Re-Sign " onclick="ClearSignature();">
<asp:Button runat="server" ID="btnSave" Text=" Save " onmousedown="document.getElementById('btnSave').value = 'Wait...';"
OnClientClick="DirectSave();" OnClick="btnSave_Click" />
</div>
</form>
<script language="javascript" type="text/javascript">
// This is the method that is directly called, this will save signature
// and then call server code to do further processing. You can change
// the delay of 5 seconds as per your needs
function DirectSave() {
SaveSignature();
var date = new Date();
var curDate = null;
// delay of 5 seconds, 5000 milisecons, change as per requirement
do { curDate = new Date(); }
while (curDate - date < 5000);
return true;
}
</script>
</body>
</html>
Open the .ascx markup file of the user control. It should read something like this:
<%# Control
Language="C#"
AutoEventWireup="true"
CodeFile="ctlSignature.ascx.cs"
Inherits="WebSignatureCapture.SignatureControl.ctlSignature" %>
Modify it to:
<%# Control
Language="C#"
AutoEventWireup="true"
CodeBehind="ctlSignature.ascx.cs"
Inherits="WebSignatureCapture.SignatureControl.ctlSignature" %>
Notice CodeFile -> CodeBehind.
Someone I know had a similar problem a while back, and then they found something that they could do something in the BeginRequest which sorted his problem and allowed him to use server controls in views. I did a quick search for it, and I believe that this is what he used.
Code below:
void Application_BeginRequest(object sender, EventArgs e)
{
var form = HttpContext.Current.Request.Form;
form.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(form, false, null);
// Refinement 1:
foreach (var key in form.AllKeys.Where(key => key.Contains("$")))
{
var value = formkey;
form.Remove(key);
var newKey = key.Substring(key.LastIndexOf("$") + 1);
form.Add(newKey, value);
}
}

POST data getting 'lost' somewhere

UPDATE
So it turns out internet exploder's stranglehold on "security" to "make up" for being so bad at security was causing my problems. I should have checked that out first haha. Thanks everyone for the input, it has given me ideas on how to optimize my application :D
I am writing a web app (in ASP.NET 3.5) that integrates with a platform app. The platform app takes the user's credentials and puts them into an "empty" HTML page that consists of a form with hidden items containing said credentials and POSTS to the webapp (default.aspx):
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JSCRIPT>
function OnLoad(){
try {
document.form1.submit();
}
catch(e){
}
}
</SCRIPT>
</HEAD>
<BODY OnLoad="OnLoad()">
<FORM ACTION="http://localhost:51816/gs_ontheweb/default.aspx" METHOD=POST NAME=form1 TARGET="_NEW">
<INPUT TYPE="HIDDEN" NAME="ClientID" VALUE="123456">
<INPUT TYPE="HIDDEN" NAME="Password" VALUE="2830088828">
<INPUT TYPE="HIDDEN" NAME="PracType" VALUE="051">
<INPUT TYPE="HIDDEN" NAME="Encrypt" VALUE="12345620081111">
</FORM>
</BODY>
</HTML>
When my default.aspx page gets loaded up, it calls the following function:
Dim ClientID As String = Request.Form("ClientID")
Dim PassWord As String = Request.Form("Password")
Dim PracType As String = Request.Form("PracType")
Each one of them result in empty strings. Any ideas on why this is happening? Thanks in advance.
EDIT: Is there something I need to configure in my web.config file to make this work properly? Request.Params("<param name>") does not work.
Your issue is the "Target" property on the Form. Why is this here?
(I also took the liberty of cleaning your HTML up a little)
<html>
<head>
<title>Test JS Post</title>
<script type="text/javascript" language="javascript">
<!--
function OnLoad(){
try
{
alert("Posting...");
document.form1.submit();
}
catch(e)
{
alert("ERROR!");
alert(e);
}
}
//-->
</script>
</head>
<body onload="OnLoad()">
<form action="http://localhost:49684/Default.aspx" method="post" name="form1">
<input type="hidden" name="ClientID" value="123456" />
<input type="hidden" name="Password" value="2830088828" />
<input type="hidden" name="PracType" value="051" />
<input type="hidden" name="Encrypt" value="12345620081111" />
<h1>This is in the form. Submit me here:</h1><input type="submit" value="foo" />
</form>
</body>
</html>
In the code behind of Default.aspx:
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
For Each value As String In Request.Form.Keys
Debug.WriteLine(String.Format("{0} = ""{1}""", value, Request.Form.Item(value)))
Next
End Sub
That HTML is just on the user's harddrive? Maybe the browser security won't let that POST because it's deemed to be a risk.
As a test -- take that exact HTML file and put it on your webserver and then browse to it. If it works, might be the browser refusing to send the data. You could check with Fiddler (for IE) or Firebug in FireFox.
Why not use System.Net.WebClient?
Some sample code (sorry, it's C#. Looks like your looking for VB. I can't translate quickly.)
System.Net.WebClient wc = new System.Net.WebClient();
byte[] b;
byte[] res;
string formdata = "text=test text&password=secret&checkbox=on&textarea=a longer text sentence&submit=submit";
// encode the form data string into a byte array
b = System.Text.Encoding.ASCII.GetBytes(formdata);
// set the content type for a form
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// POST and get data
res = wc.UploadData("http://localhost:51816/gs_ontheweb/default.aspx", b);
//convert the return page from byte[] to ascii
string s = System.Text.Encoding.ASCII.GetString(res);

Resources