I have to create a simple website using asp.net web forms, but I'm required to not use any server controls i.e. runat="server"
I have the following:
HTML
<form method="post" action="">
<label for="name">Name</label>
<input id="name" name="name" type="text" />
<input value="Save" type="submit" />
</form>
Code behind
protected void myFunction()
{
// do something
}
I'm currently putting // do something in the protected void Page_Load(object sender, EventArgs e) function, but I would like to call it when the save button is clicked. However I don't know how to do this without using runat="server". Is there a way of achieving this?
The real answer to this question is in the comment:
Using webforms but saying no runat="server" is like saying go kayaking, but no paddles. It sounds more like you should be using ASP.NET MVC
I'll add ASP.Net Web Pages as well for getting things done quickly (note: this doesn't mean ASP.Net Web Pages are only for "simple" sites - you can do whatever you want with it).
I have to create a simple website using asp.net web forms
But since it "has to" be WebForms it's still doable. Is it advisable? nope - particularly with aforementioned options as well as other comments on SPA/Javascript/XHR.
End of day, it's still HTTP Requests, and Responses, so standard HTML form inputs and such work just like in any other "framework":
the "front end" (well, Page is technically a control but we're sticking to WebForms so this will be the only "server control"):NoServerControls.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="NoServerControls.aspx.cs" Inherits="WebForms.NoServerControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Humor Me Batman</title>
</head>
<body>
<form method="post">
<input type="text" name="wtf"/>
<input type="submit" value="Batman"/>
</form>
<h1>It's "classic ASP" Batman! <%= echo %></h1>
</body>
</html>
the "back end" (NoServerControls.aspx.cs code behind)
public partial class NoServerControls : System.Web.UI.Page
{
public string echo { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
//Trivial example: skipping all validation checks
//It's either a GET or POST end of day
if (Request.RequestType == "POST")
{
//Do something with data, just echoing it here
echo = Request["wtf"];
}
}
}
Hth.
Batman :)
I have a working test project on this please refer this...
<table>
<tr>
<td>Name </td>
<td>
<input type="text" id="custid" class="form-control custname" name="fullname" required />
</td>
</tr>
<tr>
<td>Designation </td>
<td>
<select id="loading" class="form-control loading">
<option value="0">Select </option>
<option value="HR">HR </option>
<option value="Engg">Engg </option>
<option value="Doctor">Doctor </option>
</select>
</td>
</tr>
<tr>
<td>Mobile No. </td>
<td>
<input type="text" id="mobile" class="form-control mobile" onkeypress="return event.charCode >=48 && event.charCode <= 57" name="fullname" required />
</td>
</tr>
<tr>
<td>Email Id </td>
<td>
<input type="text" id="emailid" class="form-control emailid" name="fullname" required />
</td>
</tr>
<tr>
<td colspan="2" id="btn">
<button type="button" onsubmit="return validateForm()" class="btn btn-primary">Save</button>
</td>
</tr>
</table>
<script>
$(document).ready(function () {
$('#btn').click(function () {
var CustNamevalidate = $('.custname').val();
if (CustNamevalidate != '') {
Name = $(".custname").val();
Loading = $(".loading").val();
Mobile = $(".mobile").val();
EmailId = $(".emailid").val();
$.ajax({
type: "POST",
url: "test.aspx/Complextype",
data: JSON.stringify({
Nam: Name, Loadin: Loading, Mobil: Mobile, EmailI: EmailId
}),
contentType: "application/json; charset=utf-8",
datatype: "json"
}).done(function (result) {
console.log(result);
alert(JSON.stringify(result));
})
}
else {
alert('Please Enter Customer Name');
}
});
});
</script>
Code Behind WEB MEthod
[WebMethod]
public static string Complextype(string Nam, string Loadin, string Mobil, string EmailI)
{
string Qtets = "Details are : Name =" + Nam + " And Designation is =" + Loadin + " And Mobileno=" + Mobil + " And EmailI=" + EmailI;
// ScriptManager.RegisterStartupScript(Page, typeof(Page), "test", "<script>alert('Sorry This Category Name Already Exist.');</script>", false);
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("usp_add_upd_emptb", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpName", Nam);
cmd.Parameters.AddWithValue("#EmpNo", Mobil);
cmd.Parameters.AddWithValue("#Desig", Loadin);
cmd.Parameters.AddWithValue("#Email", EmailI);
cmd.Parameters.AddWithValue("#id", 0);
con.Open();
cmd.ExecuteNonQuery();
if (con.State == ConnectionState.Open)
{
con.Close();
}
else
{
con.Open();
}
}
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString);
//{
//}
return Qtets;
}
you Can not call Function Directly if you are not using server controls for function to be called you need to have Web service with static function.
Related
I have created a form which to insert few data into database. I am using jquery to insert the data in my mvc project but I am getting confused in how can I create insert function.
First thing, I have created a one method to Insert or Updating the record via ID. But I don't know how can I use Id as primary to check whether to Insert or Update. I know that if my ID is equal to 0 means Insert or if greater than 0 then update but how can I add that into my function. Second, I know my Insert function does not seems to be right way but what could be easier way to implement?
(View).asmx
<script type="text/javascript">
$(document).ready(function() {
//function will be called on button click having id btnsave
$("#btnRoleListSubmit").click(function() {
$.ajax({
type: "POST", //HTTP POST Method
url: '/Admin.mvc/Admin/InsertRoleList', // Controller/View
data: { //Passing data
Name: $("#Name").val(), //Reading text box values using Jquery
Role: $("#Role").val(),
}
});
});
});
</script>
<table align="center">
<tr>
<td valign="top" width="100" class="col-label">
<span>Name</span>
</td>
<td class="col-label">
<input type="text" maxlength="200" style="margin-left: 0;" name="Name" id="Name"
class="required" value="" />
</td>
</tr>
<tr>
<td valign="top" class="col-label">
Employee Role
</td>
<td class="col-label">
<textarea id="Role" name="Role" class="required" cols="15" rows="2"></textarea>
</td>
</tr>
</table>
<hr />
<div style="margin: 12px;" align="center">
<button type="submit" name="btnRoleListSubmit" class="actionButton">
<span>Add Employee Role</span></button>
</div>
(Controller).cs
public ActionResult InsertRoleList(int branchId, RoleListViewModel obj)
{
AddDetails(branchId, obj);
return View();
}
private void AddDetails(int branchId, EmailListViewModel obj)
{
Branch branches = this._branches.GetID(branchId);
var GetDB = branches.GetClientDatabase();
RoleListViewModel listData = new RoleListViewModel();
{
listData.Name= obj.Name;
listData.Role= obj.Role;
};
List<int> lstIds = GetDB.InsertorUpadateRole(obj);
}
SqlQueries.cs
public List<int> InsertorUpadateRole (RoleList obj)
{
RoleList lstData = new RoleList();
string sqlQuery = string.Empty;
sqlQuery = #"INSERT INTO [dbo].[EmployeeRoleList]
([name],
[is_active],
[role],
[is_admin]
}
VALUES ( '{0}','1','{2}','0')
SELECT SCOPE_IDENTITY() AS id;";
try
{
this.ExecuteReader((record) =>
{
Name = Convert.ToInt32(record["name"]);
Role = Convert.ToInt32(record["role"]);
},
string.Format(sqlQuery, lstdata.Name, lstdata.Role));
}
catch (Exception e)
{
var message = e;
}
}
Can anyone help with this?
Your url usually starts with the controller, try "/Admin/InsertRoleList". Your ajax post parameters need to match the controller InsertRoleList(string Name, string Role) which is not very similar to your controller code...
I have already bind a html table using jQuery json.
I want to get multiple checkbox value using jQuery json and delete by selected multiple delete method.
This is my code for bind the table.
$(function () {
debugger
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm5.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (dt) {
debugger;
for (var i = 0; i < dt.d.length; i++) {
$("#example1 > tbody").append("<tr><td> <input type='checkbox' /></td><td>" + dt.d[i].CategoryID + "</td><td>" + dt.d[i].Name + "</td><td>" + dt.d[i].Status + "</td><td> <button type='submit'>Submit</button><button type='submit' onclick='deleteRecord(" + dt.d[i].CategoryID + ")'>Delete</button> </tr>");
}
$("#example1").DataTable();
},
error: function (result) {
alert("Error");
}
});
});
This is my Button to Delete selected(multiple delete):
<button type="button" name="deletebtn" id="deletebtn">Delete Selected</button>
This is my html table:
<div class="box-body">
<button type="button" name="deletebtn" id="deletebtn">Delete Selected</button>
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Check Box</th>
<th>Category Name</th>
<th>Category Details</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="myBody">
</tbody>
</table>
</div>
You just tell me :
1.what is the code to select all the checkbox??
2.Code to delete using multiple jquery??
The Server side Code is here For Single Delete(with out checkbox):
[WebMethod]
public static void deleteRecord(int Id)
{
clsCategoryBL objproject = new clsCategoryBL();
objproject.CategoryDelete(Id);
}
In BL:
public string CategoryDelete(int CategoryID)
{
using (KSoftEntities db = new KSoftEntities())
{
try
{
var categoryDetails = db.tblCategories.Where(i => i.CategoryID == CategoryID).SingleOrDefault();
db.tblCategories.Remove(categoryDetails);
db.SaveChanges();
return "Record deleted successfully";
}
catch (Exception ex)
{
}
return "Error on deletion";
}
}
The Delete is Occur on the Client Side by Using This code:
$().ready(function () {
$('body').on('click', '#deletebtn', function () {
debugger;
$("#example1 tr").each(function () {
var rowSelector = $(this);
if (rowSelector.find("input[type='checkbox']").prop('checked')) {
rowSelector.remove();
}
});
});
});
The Code For Bind The Table:
enter code here
protected void Page_Load(object sender, EventArgs e)
{
if (Session["adminuser"] == null)
Response.Redirect("Default.aspx");
if (!IsPostBack)
{
// Page.Title = "Category Details";
BindDatatable();
}
}
[WebMethod]
public static UserDetails[] BindDatatable()
{
clsCategoryBL objcategory = new clsCategoryBL();
List<UserDetails> details = new List<UserDetails>();
DataTable dt = new DataTable();
//var categories= clsCategoryBL.GetAllCategoryDetails("admin");
dt = objcategory.GetAllCategoryDetails("admin");
if (dt.Rows.Count > 0)
{
foreach (DataRow dtrow in dt.Rows)
{
UserDetails user = new UserDetails();
user.CategoryID = dtrow["CategoryID"].ToString();
user.Name = dtrow["Name"].ToString();
user.Status = dtrow["Status"].ToString();
details.Add(user);
}
//literal1.Text = html.ToString();
}
return details.ToArray();
}
public class UserDetails
{
public string CategoryID { get; set; }
public string Name { get; set; }
public string Status { get; set; }
}
I want To delete it on server Side that means also on my database(Sql)
So what should i do???
I Want To Delete Multiple Row By Click On Multiple CheckBox On Database Also..I have mention in above the backend code also..I want to delete the row of html table by click 2 to 3 checkbox(it may be vary depend upon the data) and click Delete Selected button..
The Table structure after pressing f12:
enter code here
<table id="example1" class="table table-bordered table-striped dataTable no-footer" role="grid" aria-describedby="example1_info">
<thead>
<tr role="row"><th class="sorting_asc" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Check Box: activate to sort column descending" style="width: 204px;">Check Box</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Category Name: activate to sort column ascending" style="width: 276px;">Category Name</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Category Details: activate to sort column ascending" style="width: 293px;">Category Details</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Status: activate to sort column ascending" style="width: 148px;">Status</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Action: activate to sort column ascending" style="width: 211px;">Action</th></tr>
</thead>
<tbody id="myBody">
<tr role="row" class="odd"><td class="sorting_1"> <input type="checkbox"></td><td>42</td><td>xyz</td><td>True</td><td> <button type="submit">Submit</button><button type="submit" onclick="deleteRecord(42)">Delete</button> </td></tr><tr role="row" class="even"><td class="sorting_1"> <input type="checkbox"></td><td>33</td><td>Advertising</td><td>True</td><td> <button type="submit">Submit</button><button type="submit" onclick="deleteRecord(33)">Delete</button> </td></tr><tr role="row" class="odd"><td class="sorting_1"> <input type="checkbox"></td><td>31</td><td>Travel & Hospitality</td><td>True</td><td> <button type="submit">Submit</button><button type="submit" onclick="deleteRecord(31)">Delete</button> </td></tr></tbody>
</table>
Assuming there is only one checkbox in a row, you could simply iterate through the rows and post to your existing [WebMethod]
Using the second column as the ID (EDIT):
$().ready(function () {
$('body').on('click', '#deletebtn', function () {
$("#example1 tr").each(function () {
var rowSelector = $(this);
if (rowSelector.find("input[type='checkbox']").prop('checked'))
{
//THE MARKUP SHOWING THE ID IS NOT AVAILABLE
//POST A TABLE ENTRY TO CLEAR UP
var id = rowSelector.find('td').first().next().html();
var sendObj = {Id : id};
//USE JSON OBJECT
$.ajax({
url : "/page.aspx/deleteRecord",//CHANGE TO YOUR URL
dataType: "json",
data: sendObj,
type: "POST",
success: function () {
alert("entry deleted");
}
});
rowSelector.remove();
}
});
});
});
Explanation
Using JQuery you simply iterate through each row and look for the checkbox value. Note you will iterate through the header as well, so if there is a checkbox there you must add logic to skip the first iteration.
EDIT 3: You will also post the ID to the server if the checkbox is checked. Important to note that you would rather post a single bulk array of ID's instead of multiple single posts, but that method has not been exposed or posted here.
Good Luck
CODE SNIPPET (CLIENT SIDE ONLY)
$().ready(function () {
$('body').on('click', '#deletebtn', function () {
$("#example1 tr").each(function () {
var rowSelector = $(this);
if (rowSelector.find("input[type='checkbox']").prop('checked'))
{
rowSelector.remove();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id='deletebtn'>DELETE</button>
<table id='example1'>
<thead>
<tr>
<th>CHECKBOX</th>
<th>NAME</th>
<th>DESCRIPTION</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type='checkbox' value='check' /></td>
<td>the name</td>
<td>the description</td>
</tr>
<tr>
<td><input type='checkbox' value='check' /></td>
<td>the name</td>
<td>the description</td>
</tr>
<tr>
<td><input type='checkbox' value='check' /></td>
<td>the name</td>
<td>the description</td>
</tr>
</tbody>
</table>
</div>
A easier method will be if you give a class to all the check-boxes in your form and then on button click you simply iterate through all the check-boxes using the class, and therby seralizing their values.
var values = $("#Myform").find(".CheckBoxClass").serialize();
here the variable value will contain the values of all the checkboxes in your form and you can send them using ajax on your server to perform further action.
You can use something like below mentioned.
$("example1 input:checkbox").prop('checked',this.checked);
Or it is answered already in below post
jquery set all checkbox checked
I want to create a checkbox that will have the "power" to check / uncheck a checkboxfor for each items presents in a list.
Here is part of the view as I built it right now (please bear with the false names and convention):
<p>
#using (Html.BeginForm("SendObj", "Manager"))
{
<p>
Select / UnSelet All Items #Html.CheckBox("selectAll", true)
</p>
<table id="objToSend">
<tr>
<th>Obj Name</th>
<th>Number In Stock</th>
(...)
</tr>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>#Html.DisplayFor(x => x[i].m_OthObj.m_ObjName)</td>
<td>#Html.DisplayFor(x => x[i].m_NbInStock)#Html.HiddenFor(x => x[i].m_NbInStock)</td>
(...)
<div id="divChckBox">
<td>
#Html.CheckBoxFor(x => x[i].m_IsSelected)
</td>
</div>
</tr>
}
</table>
<input type="submit" value="Send"/>
}
</p>
As for the "how", well, I have searched a bit around and I have tried this jquery script, but to no avail:
**** EDIT ****
Here's a new jQuery based on the comments people posted below. The alerts are there on debug purpose, and both appears when needed:
<script type="text/javascript">
$(document).ready(function() {
alert("The document is ready");
$("#selectAll").click(function() {
alert("The case has been clicked");
var chkValue = $(this).is(":checked");
$("#divChckBox").attr("checked", "checked");
});
});
</script>
I do not mind using jquery, far from it, I just do not know how it works yet. Maybe that's why what I have in mind does not work.
Can anyone help me out? Thank you!
* EDIT *
I will add here what the rendered page gives out for the checkboxes:
<td><input checked="checked" class="chckBoxList" data-val="true" data-val-required="The m_IsSelected field is required." name="[0].m_IsSelected" type="checkbox" value="true" /><input name="[0].m_IsSelected" type="hidden" value="false" /></td>
Maybe that will give out more informations on what's going on.
#Html.CheckBox("TheOneCheckBoxToRuleThemAll")
Change your current checkbox code to:
<td>#Html.CheckBoxFor(x => x[i].m_IsSelected, new{ #class = "checkGroup1"})</td>
The easiest Jquery ever (make sure to put it in document.ready like shown):
<script type="text/javascript">
$(document).ready(function () {
//alert("the document is ready");
$("#TheOneCheckBoxToRuleThemAll").click(function () {
//alert("inside my click event");
var chkValue = $(this).is(":checked");
$(".checkGroup1").prop("checked", chkValue);
});
});
</script>
EDIT:
My previous answer used the .attr() attribute. After testing, I had all sorts of trouble getting that to work. After referring to this SO post, I switched to using .prop() and everything magically began to function correctly.
Jquery .Attr()
Jquery .Prop()
EDIT:
In the example I've provided, your checkboxes MUST look like this:
<input name='itdoesnotmatter' id='donotcare' class='checkGroup1' />
also, do not use that stupid name that I put on there, use something easy like
#Html.CheckBox("MasterCheck")
I stand corrected: CheckBoxFor does NOT allow class setting
In your Helper
<div id="divChckBox">
#Html.CheckBoxFor(x => x[i].m_IsSelected)
</div>
And then make your selector group by the class:
$("#divChckBox :checkbox").attr("checked", "checked");
As there are MANY comments around and many answers, here's my current code (which works!):
<script type="text/javascript">
$(document).ready(function() {
//alert("The document is ready");
$("#selectAll").click(function() {
//alert("The case has been clicked");
var chkValue = $(this).is(":checked");
$(".divChckBox").prop("checked", chkValue);
});
});
</script>
<p>
#using (Html.BeginForm("SendObj", "Manager"))
{
<p>
Select / UnSelet All Items #Html.CheckBox("selectAll", true)
</p>
<table>
<tr>
<th>Card Name</th>
<th>Number In Stock</th>
(...)
</tr>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>#Html.DisplayFor(x => x[i].m_OthObj.m_ObjName)</td>
<td>#Html.DisplayFor(x => x[i].m_NbInStock)#Html.HiddenFor(x => x[i].m_NbInStock)</td>
(...)
<td>
<input type="checkbox" name="itdoesnotmatter" class="divChckBox" checked="true"/>
</td>
</tr>
}
</table>
<input type="submit" value="Send"/>
}
</p>
Now every checkboxes are checked or not depending on the state of the select all checkboxes! Thank you everyone.
Now I need to solve the problem of "unlinking" the result of the checkbox in my controller because a behavior was linked to this. But it's another problem.
My code works perfectly in VS2010 C# but once published to IIS7 the PartialView (list of records) does not get rendered in the View...it rolls to a new page without the data except for the correct record count retrieved from SQL server. SQL server is on separate box.
I have searched for hours on this site with no luck finding a resolution.
View with the RenderPartial:
<table style="width:100%">
<tr>
<td>
<h3>Outage Tracking List (Open or Active)</h3>
</td>
<td style="text-align:right">
<h1><%: ViewData["ApplicationName"]%></h1>
</td>
</tr>
</table>
<% Html.RenderPartial("OutageSearch",this.ViewData.Model); %>
PartialView:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<OutageTrackingWebSite.Models.OutageViewModel" %>
<div>
<script language="javascript" type="text/javascript">
function OutageSearch() {
$("#OutageSearchForm #CurrentPageNumber").val("1");
PostSearchForm();
}
Various functions then the rest of the partialview
<% using (Ajax.BeginForm("OutageSearch", null,
new AjaxOptions { UpdateTargetId = "DivOutageSearchResults", OnComplete="OutageSearchComplete" },
new { id = "OutageSearchForm" })) { %>
<table style="background-color: #ebeff2; width: 100%; border:solid 1px #9fb8e9" cellspacing="2" cellpadding="2">
<tr>
<td style="width: 60%; text-align: left">
<input id="btnSearch" onclick="OutageSearch();" type="submit" value="List Open/Active" />
</td>
</tr>
</table>
<div id="DivOutageSearchResults">
<% Html.RenderPartial("OutageSearchResults", this.ViewData.Model); %>
</div>
<% } %>
additional PartialView
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<%OutageTrackingWebSite.Models.OutageViewModel" >
<input name="CurrentPageNumber" type="hidden" id="CurrentPageNumber" value="<%=Model.CurrentPageNumber%>" />
<input name="TotalPages" type="hidden" id="TotalPages" value="<%=Model.TotalPages%>" />
<input name="SortBy" type="hidden" id="SortBy" value="<%=Model.SortBy%>" />
<input name="SortAscendingDescending" type="hidden" id="SortAscendingDescending" value="<%=Model.SortAscendingDescending%>" />
<input name="PageSize" type="hidden" id="PageSize" value="9" />
<script language="javascript" type="text/javascript">
function GetOutageDetails(OutageID) {
if (formIsDisabled == false) {
DisableForm();
formData = "OutageID=" + OutageID;
setTimeout(PostOutageIDToServer, 1000);
}
}
function PostOutageIDToServer() {
$.post("/Outage/GetOutageInformation", formData, function (data, textStatus) {
OutageUpdateComplete(data);
}, "json");
}
Controller
public ActionResult DisplayOutageList()
{
Models.OutageViewModel outageViewModel = new Models.OutageViewModel();
outageViewModel.TotalPages = 0;
outageViewModel.TotalRows = 0;
outageViewModel.CurrentPageNumber = 0;
ViewData.Model = outageViewModel;
string applicationName = Convert.ToString( System.Configuration.ConfigurationManager.AppSettings["ApplicationName"]);
ViewData["ApplicationName"] = applicationName;
return View("OutageMaintenance");
}
///
/// Outage Search
///
///
public PartialViewResult OutageSearch()
{
long totalRows;
long totalPages;
bool returnStatus;
string returnErrorMessage;
OutageBLL OutageBLL = new OutageBLL();
Models.OutageViewModel outageViewModel = new Models.OutageViewModel();
this.UpdateModel(outageViewModel);
List Outages = OutageBLL.OutageSearch(
outageViewModel,
outageViewModel.CurrentPageNumber,
outageViewModel.PageSize,
outageViewModel.SortBy,
outageViewModel.SortAscendingDescending,
out totalRows,
out totalPages,
out returnStatus,
out returnErrorMessage);
ViewData["Outages"] = Outages;
outageViewModel.TotalPages = totalPages;
outageViewModel.TotalRows = totalRows;
ViewData.Model = outageViewModel;
return PartialView("OutageSearchResults");
}
///
/// Get Outage Information
///
///
public JsonResult GetOutageInformation()
{
bool returnStatus;
string returnErrorMessage;
List returnMessage;
OutageBLL outageBLL = new OutageBLL();
Models.OutageViewModel outageViewModel = new Models.OutageViewModel();
this.TryUpdateModel(outageViewModel);
Outage outage = outageBLL.GetOutageInformation(
outageViewModel.OutageID,
out returnStatus,
out returnErrorMessage,
out returnMessage);
outageViewModel.UpdateViewModel(outage, typeof(Outage).GetProperties());
outageViewModel.ReturnMessage = returnMessage;
outageViewModel.ReturnStatus = returnStatus;
outageViewModel.OutageScheduledDate = UtilitiesBLL.FormatDate(outageViewModel.ScheduledDate);
outageViewModel.OutagePlannedDuration = UtilitiesBLL.FormatDuration(outageViewModel.PlannedDuration);
return Json(outageViewModel);
}
Check your included JavaScript files on the deployed version. If you are missing some files (MicrosoftMvcAjax.js, jQuery.js), the page could simply be posting instead of using an Ajax post.
THIS IS THE SITE.MASTER ASPX PAGE
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="Prototype4.SiteMaster" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
alert("JS code in general: OK");
$(function () {
$("#lnkShowOtherPage").click(function () {
alert("OtherPagePanel length: " + $("#OtherPagePanel").length);
alert("OtherPagePanel load: " + $("#OtherPagePanel").load);
$("#OtherPagePanel").load("/EntryForms/OpenCase.aspx");
});
});
function updateClock() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
// Pad the minutes and seconds with leading zeros, if required
currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
// Choose either "AM" or "PM" as appropriate
var timeOfDay = (currentHours < 12) ? "AM" : "PM";
// Convert the hours component to 12-hour format if needed
currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
// Convert an hours component of "0" to "12"
currentHours = (currentHours == 0) ? 12 : currentHours;
// Compose the string for display
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
// Update the time display
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
Case Management System
Welcome
!
[ ]
<%--Welcome:
!--%>
Welcome: Guest
[ Log In ]
</asp:LoginView>
<%-- [ <asp:LoginStatus ID="MasterLoginStatus" runat="server" LogoutAction="Redirect" LogoutPageUrl="~/Logout.aspx" /> ] --%>
</div>
<div class="topNav">
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
<Items>
<asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home"
ImageUrl="~/homeIcon.png"/>
<asp:MenuItem NavigateUrl="~/About.aspx" Text="About"
ImageUrl="~/aboutIcon.png"/>
<asp:MenuItem ImageUrl="~/contact_us_icon1.png" NavigateUrl="~/Contact.aspx"
Text="Contact Us" Value="Contact Us"></asp:MenuItem>
</Items>
</asp:Menu>
</div>
</div>
</div>
</div>
<div class="page" style="margin-top:5px;height:auto;">
<div class="right" style="border-style:solid;padding-left: 4px; padding-right:4px;">
<asp:Button ID="newsButton" runat="server" Text="News"
class="fnctButton" Height="25px" Width="70px" />
<div style="border-color: White; border-width:medium; border: medium;">
<p style="text-align:left; font-size:1.2em; color:White;">
This is a place holder for some real text that is displayed regarding news within the departement and additional links to external sites for news.
</p>
</div>
<asp:ContentPlaceHolder ID="RightNewsItem" runat="server"/>
</div>
<div class="left" style="border-style:solid;">
<asp:Button ID="functionButton" runat="server" Text="System Functions"
class="fnctButton" Height="25px" Width="170px" />
<asp:ContentPlaceHolder ID="LeftNavigation" runat="server">
</asp:ContentPlaceHolder>
</div>
<div class="middle" style= "border-bottom-style:solid;">
<asp:ContentPlaceHolder ID="MainContent" runat="server"/>
</div>
</div>
<div class="clear">
</div>
<div class="footer">
<span style="font-size: small;color: #FFFFFF;"><strong>Copyright 2011 JustRite Software Inc.</strong></span></div>
</form>
AND THIS ONE IS THE CASE ADMIN PAGE BASED ON THE MASTER PAGE. THERE ARE TWO BUTTONS ON THE LEFT NAVIGATION PANE THAT SHOULD LOAD A THIRD PAGE (OPENCASE OR ADDEXHIBIT) IN THE CENTRE SPACE DEPENDING ON WHICH BUTTON IS CLICKED. THE CASE ADMIN PAGE .ASPX BELOW.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CaseAdmin.aspx.cs" Inherits="Prototype4.CaseAdmin" %>
<%#PreviousPageType VirtualPath="~/Account/Login.aspx"%>
<div style="margin-top:20px; margin-bottom:20px;">
<p class="actionButton">
<a id="lnkShowOtherPage" href="#">Open Case</a>
</p>
<p class="actionButton"><asp:LinkButton ID="RegisterExhibitLinkButton"
runat="server" onclick="RegisterExhibitLinkButton_Click">Register Exhibit</asp:LinkButton> </p>
</div>
<div id="OtherPagePanel" style="width:auto">
</div>
THIS SECTION REPRESENTS THE CODE BEHIND FOR THE CASEADMIN PAGE THUS THE .CS CODES
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Prototype4
{
public partial class CaseAdmin : System.Web.UI.Page
{
//string userid;
//string strUsername;
protected void Page_Load(object sender, EventArgs e)
{
//strUsername = Session["Username"].ToString();
}
//public String AdminUserID
//{
// get
// {
// //return userid;
// }
//}
//userid = PreviousPage.AdminID;
//Response.Redirect("~/EntryForms/OpenCase.aspx", false);
/* if (PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)PreviousPage.FindControl("UserName");
if (SourceTextBox != null)
{
userid = SourceTextBox.ToString();
}
}*/
protected void RegisterExhibitLinkButton_Click(object sender, EventArgs e)
{
Response.Redirect("~/EntryForms/AddExhibit.aspx", false);
}
}
}
THIS IS ONE OF THE TWO PAGES THAT SHOULD LOAD DEPENDING ON THE BUTTON CLICK. I HAVE ATTACHED THE CODE FOR THE OPENCASE FORM SO THAT WOULD CORRESPOND WITH THE OPENCASE LINK BUTTON ON THE LEFT. OPENCASE.ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="OpenCase.aspx.cs" Inherits="Prototype4.EntryForms.OpenCase" %>
<%#PreviousPageType VirtualPath="~/CaseAdmin.aspx" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
.casePage
{
width: 430px;
height:314px;
background-color:#3a4f63;
}
.style1
{
font-weight: normal;
color: #FFFFFF;
text-align: center;
}
.style2
{
font-weight: normal;
color: Black;
text-align: left;
margin-left: 20px;
margin-top:0px;
}
.style3
{
width: 85%;
}
.style4
{
width: 175px;
background-color: #808080;
}
.style5
{
background-color: #CCCCCC;
padding-left:10px;
}
</style>
Open Case
Form
<table class="style3" align="center">
<tr>
<td class="style4">
<p class="style2">
Case ID:
</p>
</td>
<td class="style5">
<asp:TextBox ID="caseIDTextBox"
runat="server" height="22px" width="154px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style4">
<p class="style2">
Case Description:
</p>
</td>
<td class="style5">
<asp:TextBox ID="caseDescTextBox"
runat="server" height="22px" width="154px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style4">
<p class="style2">
Case Administrator ID:
</p>
</td>
<td class="style5">
<asp:TextBox
ID="caseAdminIDTextBox" runat="server" height="22px" width="154px"></asp:TextBox>
</td>
</tr>
</table>
</div>
<div>
<table class="style3" align="center">
<tr>
<td align="left">
<asp:Button ID="openCaseBotton" runat="server" Text="Open Case"
onclick="openCaseBotton_Click" />
</td>
<td align="center">
<asp:Button ID="addExhibitBotton" runat="server" Text="Add Exhibit"
onclick="addExhibitBotton_Click" />
</td>
<td align="right">
<asp:Button ID="cancelButton" runat="server" Text="Cancel"
onclick="cancelButton_Click" /></td>
</tr>
</table>
</div>
</div>
</form>
AND LASTLY THE OPENCASE.CS PAGE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
namespace Prototype4.EntryForms
{
public partial class OpenCase : System.Web.UI.Page
{
string adminString;
protected void Page_Load(object sender, EventArgs e)
{
adminString = "CA123";
}
protected void openCaseBotton_Click(object sender, EventArgs e)
{
//SQL connection string
SqlDataSource CSMDataSource = new SqlDataSource();
CSMDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["CMSSQL3ConnectionString"].ToString();
//SQL Insert command with variables
CSMDataSource.InsertCommandType = SqlDataSourceCommandType.Text;
CSMDataSource.InsertCommand = "INSERT INTO Filing (FilingID, FilingDesc, DateOpened, FilingPriority, AdministratorID) VALUES (#FilingID, #FilingDesc, #DateOpened, #FilingPriority, #AdministratorID)";
//Actual Insertion with values from textboxes into databse fields
CSMDataSource.InsertParameters.Add("FilingID", caseIDTextBox.Text);
CSMDataSource.InsertParameters.Add("FilingDesc", caseDescTextBox.Text);
CSMDataSource.InsertParameters.Add("DateOpened", DateTime.Now.ToString());
CSMDataSource.InsertParameters.Add("FilingPriority", null);
CSMDataSource.InsertParameters.Add("AdministratorID", adminString.ToString());
int rowsCommitted = 0;
//Try catch method to catch exceptions during insert
try
{
rowsCommitted = CSMDataSource.Insert();
}
catch (Exception ex)
{
//error message displayed when exception occurs
string script = "<script>alert('" + ex.Message + "');</script>";
Response.Write("The following Error occurred while entering the records into the database" + " " + ex.ToString() + " ");
Response.Redirect("~/ErrorPage.aspx", false);
}
finally
{
CSMDataSource = null;
}
//Where to go next if insert was successful or failed
if (rowsCommitted != 0)
{
Response.Redirect("~/CaseAdmin.aspx", false);
}
else
{
Response.Redirect("~/ErrorPage.aspx", false);
}
}
protected void addExhibitBotton_Click(object sender, EventArgs e)
{
Response.Redirect("~/EntryForms/AddExhibit.aspx", false);
}
protected void cancelButton_Click(object sender, EventArgs e)
{
Response.Redirect("~/CaseAdmin.aspx", false);
}
}
}
ALL I WANT TO DO IS GET THE RESPECTIVE PAGES TO LOAD INSIDE THE MAIN CONTENT AREA (THE MIDDLE SECTION) WITHOUT RELOADING THE PAGE. ITS BEEN A LONG WAY COMING BUT PROVED SUCCESSFUL WITH A LOT TO LEARN BUT I JUST WANT TO KNOW HOW I CAN APPLY THIS SAME TECHNIQUE TO THE OTHER BUTTON CLICK(ADD EXHIBIT) SINCE IN THE AJAX CODE IN THE HEADER OF THE MASTER PAGE SPECIFIES THE URL ON JUST ONE PAGE. HOW DO I DO THAT FOR SUBSEQUENT PAGES THAT USE THE MASTER PAGE AND WOULD BE DOING SIMILAR ACTIONS. FOR EXAMPLE THE CASE MANAGER PAGE THAT LOOKS LIKE THIS.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CaseManager.aspx.cs" Inherits="Prototype4.CaseManager" %>
This is a place holder for allerts about cases to which the investigator has been assigned to.
<div style="margin-top:20px; margin-bottom:20px;">
<p class="actionButton"><asp:LinkButton ID="AllocateOfficerLinkButton" runat="server">Allocate Officer</asp:LinkButton> </p>
<p class="actionButton"><asp:LinkButton ID="ReallocateLinkButton" runat="server">Reallocate Officer</asp:LinkButton> </p>
<p class="actionButton"><asp:LinkButton ID="SetPriorityLinkButton" runat="server">Prioritize Case</asp:LinkButton> </p>
<p class="actionButton"><asp:LinkButton ID="OpenCaseLinkButton" runat="server">Open Case</asp:LinkButton> </p>
<p class="actionButton"><asp:LinkButton ID="RegisterExhibitLinkButton" runat="server">Register Exhibit</asp:LinkButton> </p>
</div>
I WANT TO TO DO SOMETHING SIMILAR LIKE IN THE CASE ADMIN PAGE BUT AM WONDERING WHAT THE CODES WILL ADD UP TO BE LIKE IN THE MASTER PAGE.
THANKS...
I actually just wanted to load a form
that is created in another asp. page
into the main content area...
I fear that what you need is not UpdatePanel but rather "ordinary" AJAX loading that other page contents into some element.. using jQuery it's as simple as:
$("#OtherPagePanel").load("OtherPage.aspx");
Where OtherPagePanel is the ID of some element in your .aspx code.
You can pass parameters to the other page over the URL, if you need to Post data it's still possible but requires some extra lines - let us know in such case.
Edit:
In the placeholder where you want the data from other page to appear, have this:
<div id="OtherPagePanel"></div>
Have such link in the other placeholder: (no need in LinkButton, ordinary HTML link is enough)
<a id="lnkShowOtherPage" href="#">Show other page</a>
Now in the <head> section of your master page add this code and it's all done:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#lnkShowOtherPage").click(function() {
$("#OtherPagePanel").load("OtherPage.aspx");
});
});
</script>
You can also copy the jQuery.min.js file to your own server and change the src accordingly.
Edit 2:
In order to debug add such lines to the code, it will tell what went wrong:
<script type="text/javascript">
alert("JS code in general: OK");
$(function() {
alert("Page load: OK");
$("#lnkShowOtherPage").click(function() {
alert("Link click: OK");
$("#OtherPagePanel").load("OtherPage.aspx");
});
});
</script>
Reload the page and let us know what alerts you get.
Edit 3:
Based on the previous debug results, have this code now:
<script type="text/javascript">
$(function() {
$("#lnkShowOtherPage").click(function() {
alert("OtherPagePanel length: " + $("#OtherPagePanel").length);
alert("OtherPagePanel load: " + $("#OtherPagePanel").load);
$("#OtherPagePanel").load("OtherPage.aspx");
});
});
</script>
Edit 4 and hopefully last:
In order to load different page into different div by clicking different button in addition to everything you already have, have such code:
<script type="text/javascript">
$(function() {
$("#lnkShowOtherPage").click(function() {
$("#OtherPagePanel").load("OtherPage.aspx");
});
$("#lnkShowDifferentOtherPage").click(function() {
$("#DifferentOtherPagePanel").load("DifferentOtherPage.aspx");
});
});
</script>
Is it a postback trigger or an async postback trigger?
i think you can register controls as post back or async on a script manager level with:
Control oControl;
ScriptManager1.RegisterAsyncPostBackControl(oControl);
you could try that