ASP.NET MVC 2 View with PartialView - PartialView Opens New Page - c#

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&ltOutageTrackingWebSite.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.

Related

ASP.NET without runat="server"

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.

how to bind dynamic items to list in mvc [duplicate]

I'm developing an ASP.NET MVC 5 web with C# and .NET Framework 4.5.1.
I have this form in a cshtml file:
#model MyProduct.Web.API.Models.ConnectBatchProductViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
#if (#Model != null)
{
<h4>Producto: #Model.Product.ProductCode, Cantidad: #Model.ExternalCodesForThisProduct</h4>
using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post))
{
#Html.HiddenFor(model => model.Product.Id, new { #id = "productId", #Name = "productId" });
<div>
<table id ="batchTable" class="order-list">
<thead>
<tr>
<td>Cantidad</td>
<td>Lote</td>
</tr>
</thead>
<tbody>
<tr>
<td>#Html.TextBox("ConnectBatchProductViewModel.BatchProducts[0].Quantity")</td>
<td>#Html.TextBox("ConnectBatchProductViewModel.BatchProducts[0].BatchName")</td>
<td><a class="deleteRow"></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" id="addrow" value="Add Row" />
</td>
</tr>
</tfoot>
</table>
</div>
<p><input type="submit" value="Seleccionar" /></p>
}
}
else
{
<div>Error.</div>
}
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script src="~/js/createBatches.js"></script> <!-- Resource jQuery -->
</body>
</html>
And this is the action method:
[HttpPost]
public ActionResult Save(FormCollection form)
{
return null;
}
And the two ViewModel:
public class BatchProductViewModel
{
public int Quantity { get; set; }
public string BatchName { get; set; }
}
public class ConnectBatchProductViewModel
{
public Models.Products Product { get; set; }
public int ExternalCodesForThisProduct { get; set; }
public IEnumerable<BatchProductViewModel> BatchProducts { get; set; }
}
But I get this in FormCollection form var:
But I want to get an IEnumerable<BatchProductViewModel> model:
public ActionResult Save(int productId, IEnumerable<BatchProductViewModel> model);
If I use the above method signature both parameters are null.
I want an IEnumerable because user is going to add more rows dynamically using jQuery.
This is jQuery script:
jQuery(document).ready(function ($) {
var counter = 0;
$("#addrow").on("click", function () {
counter = $('#batchTable tr').length - 2;
var newRow = $("<tr>");
var cols = "";
var quantity = 'ConnectBatchProductViewModel.BatchProducts[0].Quantity'.replace(/\[.{1}\]/, '[' + counter + ']');
var batchName = 'ConnectBatchProductViewModel.BatchProducts[0].BatchName'.replace(/\[.{1}\]/, '[' + counter + ']');
cols += '<td><input type="text" name="' + quantity + '"/></td>';
cols += '<td><input type="text" name="' + batchName + '"/></td>';
cols += '<td><input type="button" class="ibtnDel" value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
$('#addrow').attr('disabled', false).prop('value', "Add Row");
});
});
Any idea?
I have checked this SO answer, and this article but I don't get my code working.
You need to generate the controls for the collection in a for loop so they are correctly named with indexers (note that property BatchProducts needs to be IList<BatchProductViewModel>
#using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post))
{
....
<table>
....
#for(int i = 0; i < Model.BatchProducts.Count; i++)
{
<tr>
<td>#Html.TextBoxFor(m => m.BatchProducts[i].Quantity)</td>
<td>#Html.TextBoxFor(m => m.BatchProducts[i].BatchName)</td>
<td>
// add the following to allow for dynamically deleting items in the view
<input type="hidden" name="BatchProducts.Index" value="#i" />
<a class="deleteRow"></a>
</td>
</tr>
}
....
</table>
....
}
Then the POST method needs to be
public ActionResult Save(ConnectBatchProductViewModel model)
{
....
}
Edit
Note: Further to your edit, if you want to dynamically add and remove BatchProductViewModel items in he view, you will need to use the BeginCollectionItem helper or a html template as discussed in this answer
The template to dynamically add new items would be
<div id="NewBatchProduct" style="display:none">
<tr>
<td><input type="text" name="BatchProducts[#].Quantity" value /></td>
<td><input type="text" name="BatchProducts[#].BatchName" value /></td>
<td>
<input type="hidden" name="BatchProducts.Index" value ="%"/>
<a class="deleteRow"></a>
</td>
</tr>
</div>
Note the dummy indexers and the non-matching value for the hidden input prevents this template posting back.
Then the script to add a new BatchProducts would be
$("#addrow").click(function() {
var index = (new Date()).getTime(); // unique indexer
var clone = $('#NewBatchProduct').clone(); // clone the BatchProducts item
// Update the index of the clone
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
$("table.order-list").append(clone.html());
});
In your Post Methode you receive "MyProduct.Web.API.Models.ConnectBatchProductViewModel" as Parameter.
Use the existing model for the Post methode.
Why do you want a IEnumerable from your model? there is only one available including the id in the model.
you can visit this article for complete source code with a video tutorial.
you have to create an action first, from where we can pass the list of object
[HttpGet]
public ActionResult Index()
{
List<Contact> model = new List<Contact>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
model = dc.Contacts.ToList();
}
return View(model);
}
then we need to create a view for that action
#model List<UpdateMultiRecord.Contact>
#{
ViewBag.Title = "Update multiple row at once Using MVC 4 and EF ";
}
#using (#Html.BeginForm("Index","Home", FormMethod.Post))
{
<table>
<tr>
<th></th>
<th>Contact Person</th>
<th>Contact No</th>
<th>Email ID</th>
</tr>
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td> #Html.HiddenFor(model => model[i].ContactID)</td>
<td>#Html.EditorFor(model => model[i].ContactPerson)</td>
<td>#Html.EditorFor(model => model[i].Contactno)</td>
<td>#Html.EditorFor(model => model[i].EmailID)</td>
</tr>
}
</table>
<p><input type="submit" value="Save" /></p>
<p style="color:green; font-size:12px;">
#ViewBag.Message
</p>
}
#section Scripts{
#Scripts.Render("~/bundles/jqueryval")
}
and then we have to write code for save the list of object to the database
[HttpPost]
public ActionResult Index(List<Contact> list)
{
if (ModelState.IsValid)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
foreach (var i in list)
{
var c = dc.Contacts.Where(a =>a.ContactID.Equals(i.ContactID)).FirstOrDefault();
if (c != null)
{
c.ContactPerson = i.ContactPerson;
c.Contactno = i.Contactno;
c.EmailID = i.EmailID;
}
}
dc.SaveChanges();
}
ViewBag.Message = "Successfully Updated.";
return View(list);
}
else
{
ViewBag.Message = "Failed ! Please try again.";
return View(list);
}
}
using(Html.BeginForm())
{
// code here
}
While to Post form Data all tags must be included form tag.
Following the principle of DRY, you can create one EditorTemplate for that purpose.
Steps:
1- In Views > Shared > Create new folder named (EditorTemplates)
2- Create a view inside your newly created EditorTemplates folder , the view's model should be BatchProductViewModel according to the OP example. Place your code inside the Editor view. No loop or index is required.
An EditorTemplate will act similar to a PartialView for every child entity but in a more generic way.
3- In your parent entity's view, call your Editor :
#Html.EditorFor(m => m.BatchProducts)
Not only this provides a more organized views, but also let's you re-use the same editor in other views as well.

How to pass data from view to controller in ASP.NET MVC? [duplicate]

I'm developing an ASP.NET MVC 5 web with C# and .NET Framework 4.5.1.
I have this form in a cshtml file:
#model MyProduct.Web.API.Models.ConnectBatchProductViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
#if (#Model != null)
{
<h4>Producto: #Model.Product.ProductCode, Cantidad: #Model.ExternalCodesForThisProduct</h4>
using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post))
{
#Html.HiddenFor(model => model.Product.Id, new { #id = "productId", #Name = "productId" });
<div>
<table id ="batchTable" class="order-list">
<thead>
<tr>
<td>Cantidad</td>
<td>Lote</td>
</tr>
</thead>
<tbody>
<tr>
<td>#Html.TextBox("ConnectBatchProductViewModel.BatchProducts[0].Quantity")</td>
<td>#Html.TextBox("ConnectBatchProductViewModel.BatchProducts[0].BatchName")</td>
<td><a class="deleteRow"></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" id="addrow" value="Add Row" />
</td>
</tr>
</tfoot>
</table>
</div>
<p><input type="submit" value="Seleccionar" /></p>
}
}
else
{
<div>Error.</div>
}
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script src="~/js/createBatches.js"></script> <!-- Resource jQuery -->
</body>
</html>
And this is the action method:
[HttpPost]
public ActionResult Save(FormCollection form)
{
return null;
}
And the two ViewModel:
public class BatchProductViewModel
{
public int Quantity { get; set; }
public string BatchName { get; set; }
}
public class ConnectBatchProductViewModel
{
public Models.Products Product { get; set; }
public int ExternalCodesForThisProduct { get; set; }
public IEnumerable<BatchProductViewModel> BatchProducts { get; set; }
}
But I get this in FormCollection form var:
But I want to get an IEnumerable<BatchProductViewModel> model:
public ActionResult Save(int productId, IEnumerable<BatchProductViewModel> model);
If I use the above method signature both parameters are null.
I want an IEnumerable because user is going to add more rows dynamically using jQuery.
This is jQuery script:
jQuery(document).ready(function ($) {
var counter = 0;
$("#addrow").on("click", function () {
counter = $('#batchTable tr').length - 2;
var newRow = $("<tr>");
var cols = "";
var quantity = 'ConnectBatchProductViewModel.BatchProducts[0].Quantity'.replace(/\[.{1}\]/, '[' + counter + ']');
var batchName = 'ConnectBatchProductViewModel.BatchProducts[0].BatchName'.replace(/\[.{1}\]/, '[' + counter + ']');
cols += '<td><input type="text" name="' + quantity + '"/></td>';
cols += '<td><input type="text" name="' + batchName + '"/></td>';
cols += '<td><input type="button" class="ibtnDel" value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
$('#addrow').attr('disabled', false).prop('value', "Add Row");
});
});
Any idea?
I have checked this SO answer, and this article but I don't get my code working.
You need to generate the controls for the collection in a for loop so they are correctly named with indexers (note that property BatchProducts needs to be IList<BatchProductViewModel>
#using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post))
{
....
<table>
....
#for(int i = 0; i < Model.BatchProducts.Count; i++)
{
<tr>
<td>#Html.TextBoxFor(m => m.BatchProducts[i].Quantity)</td>
<td>#Html.TextBoxFor(m => m.BatchProducts[i].BatchName)</td>
<td>
// add the following to allow for dynamically deleting items in the view
<input type="hidden" name="BatchProducts.Index" value="#i" />
<a class="deleteRow"></a>
</td>
</tr>
}
....
</table>
....
}
Then the POST method needs to be
public ActionResult Save(ConnectBatchProductViewModel model)
{
....
}
Edit
Note: Further to your edit, if you want to dynamically add and remove BatchProductViewModel items in he view, you will need to use the BeginCollectionItem helper or a html template as discussed in this answer
The template to dynamically add new items would be
<div id="NewBatchProduct" style="display:none">
<tr>
<td><input type="text" name="BatchProducts[#].Quantity" value /></td>
<td><input type="text" name="BatchProducts[#].BatchName" value /></td>
<td>
<input type="hidden" name="BatchProducts.Index" value ="%"/>
<a class="deleteRow"></a>
</td>
</tr>
</div>
Note the dummy indexers and the non-matching value for the hidden input prevents this template posting back.
Then the script to add a new BatchProducts would be
$("#addrow").click(function() {
var index = (new Date()).getTime(); // unique indexer
var clone = $('#NewBatchProduct').clone(); // clone the BatchProducts item
// Update the index of the clone
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
$("table.order-list").append(clone.html());
});
In your Post Methode you receive "MyProduct.Web.API.Models.ConnectBatchProductViewModel" as Parameter.
Use the existing model for the Post methode.
Why do you want a IEnumerable from your model? there is only one available including the id in the model.
you can visit this article for complete source code with a video tutorial.
you have to create an action first, from where we can pass the list of object
[HttpGet]
public ActionResult Index()
{
List<Contact> model = new List<Contact>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
model = dc.Contacts.ToList();
}
return View(model);
}
then we need to create a view for that action
#model List<UpdateMultiRecord.Contact>
#{
ViewBag.Title = "Update multiple row at once Using MVC 4 and EF ";
}
#using (#Html.BeginForm("Index","Home", FormMethod.Post))
{
<table>
<tr>
<th></th>
<th>Contact Person</th>
<th>Contact No</th>
<th>Email ID</th>
</tr>
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td> #Html.HiddenFor(model => model[i].ContactID)</td>
<td>#Html.EditorFor(model => model[i].ContactPerson)</td>
<td>#Html.EditorFor(model => model[i].Contactno)</td>
<td>#Html.EditorFor(model => model[i].EmailID)</td>
</tr>
}
</table>
<p><input type="submit" value="Save" /></p>
<p style="color:green; font-size:12px;">
#ViewBag.Message
</p>
}
#section Scripts{
#Scripts.Render("~/bundles/jqueryval")
}
and then we have to write code for save the list of object to the database
[HttpPost]
public ActionResult Index(List<Contact> list)
{
if (ModelState.IsValid)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
foreach (var i in list)
{
var c = dc.Contacts.Where(a =>a.ContactID.Equals(i.ContactID)).FirstOrDefault();
if (c != null)
{
c.ContactPerson = i.ContactPerson;
c.Contactno = i.Contactno;
c.EmailID = i.EmailID;
}
}
dc.SaveChanges();
}
ViewBag.Message = "Successfully Updated.";
return View(list);
}
else
{
ViewBag.Message = "Failed ! Please try again.";
return View(list);
}
}
using(Html.BeginForm())
{
// code here
}
While to Post form Data all tags must be included form tag.
Following the principle of DRY, you can create one EditorTemplate for that purpose.
Steps:
1- In Views > Shared > Create new folder named (EditorTemplates)
2- Create a view inside your newly created EditorTemplates folder , the view's model should be BatchProductViewModel according to the OP example. Place your code inside the Editor view. No loop or index is required.
An EditorTemplate will act similar to a PartialView for every child entity but in a more generic way.
3- In your parent entity's view, call your Editor :
#Html.EditorFor(m => m.BatchProducts)
Not only this provides a more organized views, but also let's you re-use the same editor in other views as well.

Javascript - Check checkbox if Multiple Checkboxes selected

I was wondering if someone could help me with some javascript as I'm quite unfamilar with it and unfortunately have been tasked with writing a function for tomorrow, and I appear to be failing miserably.
In my MVC application, I have a View where the user can select multiple outlets within a particular groupHeader. Already written was SelectAll, and DeselectAll javascript functions to select all (or deselect all) outlets within a groupHeader, however I am unsure how to use these functions within other functions.
I need to limit the existing functionality which will only allow the user to select the groupHeader, and this should select all the outlets within that group. Unfortunately this part of the application affects other parts so the underlying functionality must remain the same.
What I would ideally like is to have javascript to do the following:
If the groupHeader checkbox is checked, call the selectAll function.
If the groupHeader checkbox is unchecked, call the deselectAll function.
As the selections need to be remembered, which would be figured out from the controller, it would also be necessary to have the following functions:
On page load, if all outlets are checked in particular section, check the groupHeader checkbox.
On page load, if all outlets are unchecked in particular section, uncheck the groupHeader checkbox.
Here is the view:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.1.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/FormHelpers.js" type="text/javascript"></script>
<script type="text/javascript">
function selectAll(sectionId) {
toggle(sectionId, "checked");
}
function deselectAll(sectionId) {
toggle(sectionId, null);
}
function toggle(sectionId, checked) {
$('[section$=' + sectionId + ']').each(function () { $(this).attr('checked', checked); });
}
</script>
<div>
<% int i = 0; %>
<% Html.BeginForm(); %>
<% { %>
<% foreach (App.Web.Models.OutletGroup g in Model.Groups) %>
<% { %>
<div style="width:700px;">
<div style="border-bottom: 1px solid;">
<div style="font-weight: bold; font-size: larger; width: 300px; float: left;">
<input type="checkbox" id="GrpHdr" /> <%: g.GroupHeader%>
</div>
<div style="line-height: 18px; vertical-align: middle; width: 250px; float: left;">
<a id="select" href="javascript:selectAll(<%: i %>)" <%: ViewData["GROUP_ALL_SELECTED_" + g.GroupHeader] %>>
Select All</a> / <a id="deselect" href="javascript:deselectAll(<%: i %>)" <%: ViewData["GROUP_ALL_SELECTED_" + g.GroupHeader] %>>
Deselect All</a>
</div>
<div style="clear: both;">
</div>
</div>
</div>
<div style="margin-left: 10px; margin-top: 10px;">
<% foreach (App.Data.Outlet outlet in g.Outlets) %>
<% { %>
<div style="float: left; line-height: 18px; padding: 2px; margin: 2px; vertical-align: middle;
border: 1px solid grey; width: 282px;">
<input type="checkbox" section="<%: i %>" name="OUTLET_<%: outlet.OutletID %>" <%: ViewData["OUTLET_" + outlet.OutletID] %>
style="vertical-align: middle; padding-left: 5px;" />
<%= Html.TrimTextToLength(outlet.Name)%>
</div>
<% } %>
</div>
<div style="clear: both; margin-bottom: 5px;">
</div>
<% i++; %>
<% } %>
<br />
<br />
<div class="buttonFooter">
<input type="submit" value="Update" />
</div>
<div style="clear: both;">
</div>
<% } %>
</div>
</asp:Content>
Here is the controller code also:
public class OutletsController : Controller
{
public ActionResult Index()
{
// Get all the outets and group them up.
//
ModelContainer ctn = new ModelContainer();
var groups = ctn.Outlets.GroupBy(o => o.Header);
OutletViewModel model = new OutletViewModel();
foreach (var group in groups)
{
OutletGroup oGroup = new OutletGroup()
{
GroupHeader = group.Key,
};
model.Groups.Add(oGroup);
}
foreach (var group in model.Groups)
{
group.Outlets = ctn.Outlets.Where(o => o.Header == group.GroupHeader).ToList();
}
// Get the existing details and check the necessary boxes (only read undeleted mappings).
//
var currentOutlets = ctn.UserOutlets.Where(uo => uo.UserID == UserServices.CurrentUserId && !uo.Deleted);
foreach (var outlet in currentOutlets)
{
ViewData["OUTLET_" + outlet.OutletID] = "checked='checked'";
}
return View(model);
}
[HttpPost]
public ActionResult Index(FormCollection formValues)
{
// Update the existing settings.
//
ModelContainer ctn = new ModelContainer();
var outlets = ctn.UserOutlets.Where(uo => uo.UserID == UserServices.CurrentUserId);
foreach (var outlet in outlets)
{
outlet.Deleted = true;
outlet.UpdatedDate = DateTime.Now;
outlet.UpdatedBy = UserServices.CurrentUserId;
}
// Save all the selected Outlets.
//
foreach (string o in formValues.Keys)
{
if (o.StartsWith("OUTLET_"))
{
UserOutlet uo = new UserOutlet();
uo.UserID = UserServices.CurrentUserId;
uo.OutletID = int.Parse(o.Substring("OUTLET_".Length));
uo.CreatedDate = DateTime.Now;
uo.CreatedBy = UserServices.CurrentUserId;
ctn.UserOutlets.AddObject(uo);
}
}
ctn.SaveChanges();
return RedirectToAction("Index");
}
}
I'd be very grateful if anyone could offer some help, or point me in the right direction.
Thanks!
EDIT:
Edited the javascript to include the following as suggested by Tejs:
$('.GrpHdr').each(function()
{
var elements = $(this).find('input[name|="OUTLET_"]');
var checkboxCount = elements.filter(':checked').length;
if (checkboxCount == elements.length)
$('.GrpHdr').attr('checked', this.checked);
else if (checkboxCount == 0)
$('.GrpHdr').attr('checked', !this.checked);
});
However I can't seem to get this to work for me. Can anyone see what's going wrong?
First, you need to change the GrpHdr checkbox to use a class or something; currently, it looks like you generate multiple checkboxes with the same Id which is never good. Assuming you change it to a class like so:
<input type="checkbox" class="GrpHdr" />
Then you can write something like this to check the checked status:
$('.GrpHdr').each(function()
{
var elements = $(this).find('input[name|="OUTPUT_"]');
var checkboxCount = elements.filter(':checked').length;
if(checkboxCount == elements.length)
// All Checked, Do Some Logic
else if(checkboxCount == 0)
// None checked, do some logic
else
// Some Checked and some not checked
});

Is it possible to reference a linkbotton outside an update panel as the update trigger?

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

Categories

Resources