// problem refreshing value
code behind file dynamically creates a checkbox, aspx file contains javascript that is invoked
when the checkbox is checked see below:
//javascript
function checkBoxClicked(sender)
{
var hdnfldVariable = document.getElementById('hcompare');
if (sender.checked == true) {
sCompareAuditVersion = sender.value;
}
document.getElementById('hcompare').value = sCompareAuditVersion;
}
//aspx file -
I have used a hidden field to pass to code behind file and have initialize value with 'x' to
//ensure that value changes
<form id="form1" runat="server">
<div class="lowSectionClass">
<asp:HiddenField id="hcompare" value="X" runat="server">
</asp:HiddenField>
//code behind file dynamically builds chekbox
public class Report : Page
{
protected HiddenField hcompare;
private string populateCalculations(int tabID, int programID, int participantID)
{
string str = "";
str = ((((str + "<br /><br /><center><table cellpadding='0' cellspacing='10'>" + "<tr class='HeadingCellText'>") + "<td>Audit Version</td>" + "<td></td>") + "<td>Calculation Set</td>" + "<td></td>") + "<td>Run Calcs/Print Report/Print CSB</td>" + "<td></td>") + "<td>Compare?</td>" + "</tr>";
DataTable infoList = new DataTable();
infoList = new ReportClass().GetInfoList(programID);
if (infoList.Rows.Count > 0)
{
for (int i = 0; i < infoList.Rows.Count; i++) // 1 = a audit, 2 = b audit, 3 = c audit.....
{
if ((i % 2) == 0) //audit 'a' = 0, audit 'b' = 1
{
str = string.Concat(new object[] { str, "<td>", infoList.Rows[i]["dtCalcDate"], "</td>" }) + "<td></td>";
str = string.Concat(new object[] { str, "<td>Run Calcs | <a href=\"javascript:setPrintVariables(", programID, ",", participantID, ",'",
infoList.Rows[i]["sAuditVersion"].ToString(), "');section_CallBack('build');\">Print Report</a> | <a href=\"ReportViewer.aspx?ProgramID=", programID, "&ParticipantID=", participantID, "&AuditVersion=",
infoList.Rows[i]["sAuditVersion"].ToString(),"&CompareAuditVersion=", hcompare.Value,"&csb=1\" target='blank'>Print CSB</a></td>"
}) + "<td></td>";
// above is where the hidden field is assigned to be passes in as a parameters and the value is not being updated
// below is where the checkbox is created and assigned function 'checkBoxClicked(this)'
str = string.Concat(new object[] { str, "<td><input id='Checkbox", i, "' tabindex='", i, "' value='", infoList.Rows[i]["sAuditVersion"].ToString(), "' onclick='checkBoxClicked(this)' type='checkbox' /></td>" }) + "</tr>";
}
}
}
return (str + "</tfoot>" + "</table></center>");
}
}
Set clientidmode = static for your hidden field
<form id="form1" runat="server">
<div class="lowSectionClass">
<asp:HiddenField id="hcompare" value="X" clientIdMode="static" runat="server">
</asp:HiddenField>
</div>
</form>
Related
I'm trying to generate a list on user selection with the help of json in MVC. On page load the list will contain all the images but when the user clicks a link specifying a particular image group. Then images in that group should be shown only.
The problem is however all the images are loaded successfully on page. When I click the linkbutton for particular group it gives me a Json string with that group and redirects to Json actionresult.
Please help I'm very new to using Json.
Razor View:-
#foreach (var item in Model.ImageObj)
{
using (Html.BeginForm("getImageClick", "Home", new { grp = item.ImgGroup }))
{
<button class="btn btn-sm" type="submit" value="#item.ImgGroup" onclick="getImageClick()">#item.ImgGroup </button>
}
}
<div class="clearfix"></div>
<div class="table-bordered" style="margin-top:40px"></div>
<div class="container" style="margin-top:10px">
<div id="status" style="font-size:20px"></div>
<table id="tbl" class="table table-responsive table-hover table-bordered text-center" style="font-size:20px"></table>
<script language="javascript">
$("#status").text("Loading...");
$.get("getImage", null, BindData);
function BindData(Images) {
var tbl = $("#tbl");
for (var j = 0; j <= Images.length; j++) {
var newRow =
"<tr class='col-lg-4 col-md-4 col-sm-12'>" +
"<td>" + "<img src=/images/" + Images[j].Image + " " + 'alt="' + Images[j].Alt + '"' + 'style="width:200px; height:200px"' + 'class="img-thumbnail"' + " />" + "<br />" + Images[j].Description + "</td>" +
"</tr>"
// +
// "<tr class='col-md-4'>" +
//"<td class='col-md-12'>" + Images[j].Description + "</td>" +
//"</tr>"
;
tbl.append(newRow);
}
$("#status").text("Loaded");
}
$.get("getImageClick", null, BindDataNew);
function BindDataNew(ImagesNew) {
var tbl = $("#tbl");
for (var j = 0; j <= ImagesNew.length; j++) {
var newRow =
"<tr class='col-lg-4 col-md-4 col-sm-12'>" +
"<td>" + "<img src=/images/" + ImagesNew[j].Image + " " + 'alt="' + ImagesNew[j].Alt + '"' + 'style="width:200px; height:200px"' + 'class="img-thumbnail"' + " />" + "<br />" + ImagesNew[j].Description + "</td>" +
"</tr>"
// +
// "<tr class='col-md-4'>" +
//"<td class='col-md-12'>" + Images[j].Description + "</td>" +
//"</tr>"
;
tbl.append(newRow);
}
$("#status").text("Loaded");
}
</script>
Controller Methods:-
public ActionResult getImage() //JSON Collection
{
Thread.Sleep(4000);
List<ImageTbl> Images = DbContext.ImageTbls.ToList<ImageTbl>();
return Json(Images, JsonRequestBehavior.AllowGet);
}
public ActionResult getImageClick(string grp) //JSON Collection
{
Thread.Sleep(4000);
List<ImageTbl> ImagesNew = DbContext.ImageTbls.Where(x => x.ImgGroup == grp).ToList<ImageTbl>();
return Json(ImagesNew, JsonRequestBehavior.AllowGet);
}
Even though your button has an onclick event handler, It is inside a form and clicking on that will do a normal form submit. The form's action attribute value is set to getImageClick and it returns JSON data. That is the reason you are seeing json data when you click on the button.
What you should do is, prevent the normal form submit behavior so that it will execute the js code which makes the ajax call and get the data and update the DOM.
Here is the unobtrusive ajax way of doing it.
#foreach (var item in Model.ImageObj)
{
<button class="btn grpBtn"
data-url="#Url.Action("getImageClick", "Home", new { grp = item.ImgGroup})">
#item.ImgGroup
</button>
}
This will add a css class grpBtn to the button.It also add a data attribute called url with value as the relative url to the getImageClick action method with the group in the query string with key grp Now listen to the click event on this button, read the data-url value and make the ajax call to that.
$(function(){
$(document).on("click",".grpBtn",function(e){
e.preventDefault(); //prevents normal link click behavior
$("#tbl").empty(); //clear existing images
$.getJSON($(this).data("url"),function(data){
//loop through the items in data and build the markup for table
$.each(data,function(a,item)
{
var newRow="<tr><td>"+item.Image="</td><tr>"; //Fix this as needed for your use case
$("#tbl").append(newRow);
});
});
});
});
As you can see in picture, I have a form where I continuously add items to the table below.
When I click "Save all" button, it posts all the table values to "InsertBulk" method.
And this is what I did in my view. I am created a form within the table. Set name and values for each input field. Made the input fields hidden, displayed only text and then on clicking save all button it posts all those value to the InsertBulk method.
#model FYPPharmAssistant.Models.InventoryModel.Manufacturer
#{
ViewBag.Title = "Form";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
<label>Name</label><br />
#Html.EditorFor(m => m.ManufacturerName, new { htmlAttributes = new { #class = "form-control" } }) <br />
<label>Description</label><br />
#Html.EditorFor(m => m.Description, new { htmlAttributes = new { #class = "form-control" } })
<input type="submit" id="addmore" value="add" />
}
#using (Html.BeginForm("InsertBulk", "Manufacturer"))
{
<table id="table">
<tr>
<th>
name
</th>
<th>
description
</th>
</tr>
</table>
<input type="submit" id="btnsaveall" value="Save all" />
}
<script>
$(document).on('ready', function () {
$('#addmore').on('click', function () {
var $table = $("#table");
$table.append("<tr> <td><input type='hidden' name='ManufacturerName' value='" + $('#ManufacturerName').val() + "' />" + $('#ManufacturerName').val() + "</td> <td><input type='hidden' name='Description' value='" + $('#Description').val() + "'>" + $('#Description').val() + "</td> <td><a href='javascript:void(0)' onclick='removeItem(this)'>Remove</a></td></tr>");
return false;
});
});
</script>
This is my InsertBulk method.
[HttpPost]
public void InsertBulk(FormCollection coll)
{
Manufacturer m = new Manufacturer();
m.ManufacturerName = coll["ManufacturerName"];
m.Description = coll["Description"];
db.Manufacturers.Add(m);
db.SaveChanges();
}
Result :
Ans this is what I get in Result. How am I suppose to solve this ? Please help!
I also tried to count keys and loop through each in the InsertBulk method. But I think I did it all wrong.
int count = coll.Count;
if(count == 0)
{
return View("ChamForm", "Test");
}
else
{
for(int i = 0; i<count; i++)
{
Manufacturer m = new Manufacturer();
m.ManufacturerName = coll["ManufacturerName[" + i + "]"];
m.Description = coll["Description[" + i + "]"];
db.Manufacturers.Add(m);
db.SaveChanges();
}
}*
If it is so why not split contents based on comma, save each of them in two different string array. Then loop through each array's item saving name and description on each loop.
public ActionResult Student(StudentModel model, FormCollection frm)
{
string XmlData = "<Parent>";
var stuclass = frm.GetValues("stuclass");
var InstituteId = frm.GetValues("Institute");
var obtmark = frm.GetValues("obtmark");
var totalmark = frm.GetValues("totalmark");
var per = frm.GetValues("per");
int count = stuclass.Count();
for (int i = 0; i < count; i++)
{
XmlData += "<child><stuclass>" + stuclass[i] + "</stuclass>"
+ "<InstituteId>" + InstituteId[i] + "</InstituteId>"
+ "<obtmark>" + obtmark[i] + "</obtmark>"
+ "<totalmark>" + totalmark[i] + "</totalmark>"
+ "<per>" + per[i] + "</per>"
+ "</child>";
}
XmlData += "</Parent>";
model.XmlData = XmlData;
var res = studal.Insertdtl(model);
return View();
}
I'm dynamically adding multiple fileuploads to my asp.net page.
The user is able to create and delete these fileuploads from the page. The code for this is written in Javascript / JQuery:
var opleverpuntCounter = 0;
function addOpleverpunt() {
var $opleverpuntContainer = $('#opleverpuntContainer');
var div = '';
var divId = 'opleverpunt_' + opleverpuntCounter;
div = '<div id="' + divId + '"><br />Upload afbeelding situatie vooraf <input id="opleverpuntbeforefile_' + opleverpuntCounter + '" name="opleverpuntbeforefile_' + opleverpuntCounter + '" type="file" accept="image/*" capture="camera" /><br /><label for="opleverpuntdescriptionbefore_' + opleverpuntCounter + '">Situatie omschrijving vooraf</label><br /><textarea type="text" id="opleverpuntdescriptionbefore_' + opleverpuntCounter + '" name="opleverpuntdescriptionbefore_' + opleverpuntCounter + '" rows="5" cols="100"></textarea><br />Upload afbeelding situatie achteraf <input id="opleverpuntafterfile_' + opleverpuntCounter + '" name="opleverpuntafterfile_' + opleverpuntCounter + '" type="file" accept="image/*" capture="camera" /><br /><label for="opleverpuntdescriptionafter_' + opleverpuntCounter + '">Situatie omschrijving achteraf</label><br /><textarea type="text" id="opleverpuntdescriptionafter_' + opleverpuntCounter + '" name="opleverpuntdescriptionafter_' + opleverpuntCounter + '" rows="5" cols="100"></textarea><br /><input id="btn_' + opleverpuntCounter + '" type="button" value="REMOVE X" class="smallButton" /></div>';
$opleverpuntContainer.append(div);
$('#btn_' + opleverpuntCounter).click(function () { removeOpleverpunt(divId); });
opleverpuntCounter++;
}
function removeOpleverpunt(element) {
var $element = $('#' + element);
$element.remove();
}
It adds 2 fileupload controls on each addOpleverpunt() call. The name and id are both generated and unique for each fileupload.
HTML:
<div id="opleverpuntContainer">
</div>
Back at server-side I use following code to get and store the uploaded files:
for (int i = 0; i <= Request.Files.Count - 1; i++) {
HttpPostedFile PostedFile = Request.Files(i);
if (PostedFile.ContentLength > 0) {
//Store PostedFile here
//(Left out to improve question readability)
}
}
The fileuploads aren't ASP:FileUpload controls but regular input FileUpload controls.
Is there any way to differentiate between opleverpuntbeforefile_x and opleverpuntafterfile_x? (x is the generated number)
If I'm able to get the difference at serverside, I will be able to store opleverpuntbeforefile in one entity and opleverpuntafterfile in another.
Suggestions and answers in either C# or VB.NET are fine.
You can access the html control name:
for (int i = 0; i <= Request.Files.Count - 1; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
var controlName = Request.Files.Keys[i];
if (PostedFile.ContentLength > 0)
{
//Store PostedFile here
//(Left out to improve question readability)
}
}
I am generating this tags (IT,Marketing....) dynamically(codebehind) from the sql using linq to sql.
And when you click on any of the the tabs it will show the gridview as per table created in database.
But the gridview binding is done during page_load event, so everything is generated during page_load, now when you click any of the blue tabs , it will show you pre-generated gridviews.
Now i want to generate or load gridviews when i clck on [+] sign of any of the tabs and not during the page load
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div id="CONTAINER" onclick="">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="clickable mfiles" onclick="showHide('subm');changesign('signm');">
<span id="signm" class="plusMinus">[+]</span><span> M-Files<br />
</span>
</div>
<div id="subm">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>
<script>
function showHide(id) {
__doPostBack('UpdatePanel1', id);
var el = document.getElementById(id);
//if (el && el.style.display == 'block') {
// el.style.display = 'none';
//}
//else {
// el.style.display = 'block';
//}
}
function changesign(id1) {
var xy = document.getElementById(id1);
if (xy.innerHTML == "[-]") {
xy.innerHTML = "[+]";
}
else {
xy.innerHTML = "[-]";
}
}
</script>
banckend code:
protected void Page_Load(object sender, EventArgs e)
{
CONTACT_INFODataContext context = new CONTACT_INFODataContext("Data Source=BPM-IT116;Initial Catalog=FORM_GET;Persist Security Info=True;User ID=spreader;Password=Red_Sky");
var depts = context.spi_GetNoOfDept();
PlaceHolder1.Controls.Clear();
int i = 1;
foreach (spi_GetNoOfDeptResult dept in depts)
{
Literal div = new Literal();
Contact deptinfo = new Contact();
deptinfo.NAME_LAST = dept.DEPT_NAME;
deptinfo.DEPT_ID = dept.DEPT_ID.ToString();
div.Text = "<div class=\"even clickable\" onclick=\"showHide('sub" + dept.DEPT_ID + "');changesign('sign" + dept.DEPT_ID + "');\">";
div.Text += "<span id=\"sign" + dept.DEPT_ID + "\">[+]</span><span>" + dept.DEPT_NAME + "</span>";
div.Text += "</div>";
div.Text += "<div id=\"sub" + dept.DEPT_ID + "\" style=\"margin-left:15px ;\">";
//GridView gd = CreateDynamicTable(dept.DEPT_ID);
i++;
PlaceHolder1.Controls.Add(div);
PlaceHolder1.Controls.Add(new LiteralControl("</div>"));
}
private GridView CreateDynamicTable(int x)
{
GridView gd = new GridView();
gd.ID = "grd" + x;
gd.AlternatingRowStyle.CssClass = "altrowstyle1";
gd.RowStyle.CssClass = "rowstyle1";
gd.HeaderStyle.CssClass = "grdhdr";
gd.GridLines = GridLines.None;
List<Contact> contacts = new List<Contact>();
CONTACT_INFODataContext context = new CONTACT_INFODataContext("Data Source=BPM-IT116;Initial Catalog=FORM_GET;Persist Security Info=True;User ID=spreader;Password=Red_Sky");
var persons = context.spi_GetContacts();
var items = context.spi_GetDept(x);
var depts = context.spi_GetNoOfDept();
foreach (spi_GetDeptResult item in items)
{
Contact contact = new Contact();
contact.NAME_LAST = item.NAME_LAST;
contact.NAME_FIRST = item.NAME_FIRST;
contact.PHONE_CELL = item.PHONE_CELL;
contact.ADDRESS = item.ADDRESS;
contact.APT = item.APT;
contact.DEPT_ID = item.DEPT_ID.ToString();
contact.DEPT_NAME = item.DEPT_NAME;
contacts.Add(contact);
//ddl_db.Items.Add(new ListItem(person.NAME_FIRST));
}
gd.CssClass = "gdmain";
gd.DataSource = contacts;
gd.DataBind();
return gd;
}
If you use a Multiview control for your tab container then you should be able to bind your code to load the Gridview to the ActiveViewChanged event and change your ActiveViewIndex property for that Multiview when your users navigate between your tabs.
I have following in html
<div id="dvAddToGrid" runat="server">
<table style="margin-left:80%">
<tr>
<td>
<asp:LinkButton ID="lnkAddToGrid" runat="server" Text="Add New" onclick="lnkAddToGrid_Click" OnClientClick="GetValues()" Font-Underline="True"></asp:LinkButton>
</td>
</tr>
</table>
</div>
I have following in javascript
function GetValues() {
// for (i = 1; i <= 5; i++)
// {
// $("#hdnTableValues")[0].value += document.getElementById("txtSerialNo_1").value+ ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtBookName_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtAuthor_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtPublisher_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtNoOfBooks_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtRemarks_1").value + "|";
// // }
document.getElementById("lblTableValues").innerHTML = $("#hdnTableValues")[0].value ;
}
In my code behind i have
protected void lnkAddToGrid_Click(object sender, EventArgs e)
{
DataTable dtBookList = new DataTable();
dtBookList.Columns.Add("SerialNo");
dtBookList.Columns.Add("BookName");
dtBookList.Columns.Add("Author");
dtBookList.Columns.Add("Publisher");
dtBookList.Columns.Add("NoOfBooks");
dtBookList.Columns.Add("Remarks");
string str = lblTableValues.Text ;
for(int i=1;i<5;i++)
{
DataRow dtRow = dtBookList.NewRow();
//hdnTableValues.Value
}
dvBookList.Visible = false;
dvAddToGrid.Visible = false;
}
Problem is i am getting values in lblTableValues in js.But in code behid it does not contain any values its value is "".Can anybody help to get the value contained in hdnTableValues in click event in code behind.
You can use a hidden input with runat="server" to handle this. Store the value to the hidden field in JavaScript. And you can access the field value in C# code behind.
HTML
<input type="hidden" id="txtHidData" runat="server" />
JavaScript
document.getElementById ( "txtHidData" ).value = "your value";
C#
string valueInCodeBehind = txtHidData.Value;
Use the asp:HiddenField control like this: (jquery example)
in the page or control:
<asp:HiddenField ID="Hidden1" runat="server" Value="blank" />
<asp:PlaceHolder runat="server">
<script type ="text/javascript">
$(function () {
//get the id of the hidden control
var clientID = "<%= Hidden1.ClientID %>";
$("#" + clientID).val("this is from the client");
});
</script>
</asp:PlaceHolder>
In a button or submit method in code behind:
Debug.WriteLine("val: " + Hidden1.Value);