Need to get a field editable depending on a field content in EXT.NET. Get this.field.msgTarget is null or not an object error - ext.net

I try to use your example to dynamically add/remove editor and get this error:
this.field.msgTarget is null or not an object error. I'm new to the ext.net - could somebody help me?
Thanks,
Jenny
this is my code:
EditExample.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="EditExample.aspx.cs" Inherits="myApp.EditExample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var setEditor = function (e) {
var column = e.grid.getColumnModel().columns[e.column],
ed = column.getCellEditor(e.row);
if (ed && (e.value != null || e.value != '')) {
ed.destroy();
}
else {
column.setEditor(new Ext.form.TextField());
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<ext:ResourceManager runat="server" />
<ext:Store ID="extStore" runat="server" >
<Reader>
<ext:JsonReader>
<Fields>
<ext:RecordField Name = "Name" />
<ext:RecordField Name = "Code" ></ext:RecordField>
<ext:RecordField Name = "Description" ></ext:RecordField>
</Fields>
</ext:JsonReader>
</Reader>
</ext:Store>
<div>
<ext:GridPanel ID="extGrd" runat="server" StripeRows="true" TrackMouseOver="true"
StoreID="extStore" Cls="x-grid-custom"
Height="250px" Layout="fit">
<ColumnModel ID="cmFC" runat="server">
<Columns>
<ext:Column ColumnID="Name" DataIndex="Name" Header="Name">
</ext:Column>
<ext:Column ColumnID="Code" DataIndex="Code" Header="Code">
</ext:Column>
<ext:Column ColumnID="Description" DataIndex="Description" Header="Description" Editable ="true" >
<Editor>
<ext:TextField ID="TextField1" runat="server"></ext:TextField>
</Editor>
</ext:Column>
</Columns>
</ColumnModel>
<Listeners>
<BeforeEdit Fn="setEditor" />
<Render Handler="this.getColumnModel().setEditable(0, true);" />
</Listeners>
<SelectionModel>
<ext:RowSelectionModel ID="RowSelectionModel1" runat="server" SingleSelect="true" MoveEditorOnEnter="true"/>
</SelectionModel>
<LoadMask ShowMask="true" />
</ext:GridPanel>
</div>
</form>
</body>
</html>
EditExample.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace myApp
{
public class info
{
public string Name { get; set; }
public string Code { get; set; }
public string Description { get; set; }
}
public partial class EditExample : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e )
{
List<info> thisInfo = new List<info>();
thisInfo.Add( new info { Code = "1", Description = "one", Name = "one Name" } );
thisInfo.Add( new info { Code = "2", Description = "two", Name = "two Names" } );
thisInfo.Add( new info { Code = "3", Description = "three", Name = "three Names" } );
thisInfo.Add( new info { Code = "4", Description = "four", Name = "four Names" } );
thisInfo.Add( new info { Code = "5", Description = "five", Name = "five Names" } );
thisInfo.Add( new info { Code = "6", Description = "six", Name = "six Names" } );
this.extStore.DataSource = thisInfo;
this.extStore.DataBind();
}
}
EDIT:
I tried to make the field disabled and readonly.
It made the field appear disabled (greyed out), but readable.
var setEditor = function (e)
{
var column = e.grid.getColumnModel().columns[e.column],
ed = column.getCellEditor(e.row);
if (ed)
{
if (e.value != null && e.value != '')
{
ed.readOnly = true; ed.setDisabled(true);
}
else
{
ed.readOnly = false; ed.setDisabled(false);
}
}
}

You can just return false to before event.
var setEditor = function (e) {
var column = e.grid.getColumnModel().columns[e.column],
ed = column.getCellEditor(e.row);
if (ed && (e.value != '')) {
return false;
}
}

Related

Auto fields liferay in custom portlet

I have a doubt.
I have a main.jsp that includes another 2 jsp and a submit button. Both of them are part of a form.
The second one includes an auto field with a validator:
<div id="groupwork-fields" >
<div class="lfr-form-row lfr-form-row-inline">
<div class="row-fields">
<aui:input fieldParam='name' id="repetibleName" cssClass="full-size"
name="<%=AwardConstants.FIELD_OTHERS_NAME%>"
label='<%=AwardConstants.LABEL_NAME %>'
value="">
<aui:validator name="custom" errorMessage="fill-name">
function (val, fieldNode, ruleValue) {
var result = true;
var selector = document.getElementById("<portlet:namespace/>select-group").value;
if (selector == 1 && val === "") {
result = false;
}
return result;
}
</aui:validator>
</aui:input>
<aui:input cssClass="full-size"
id="email0" fieldParam='email0'
name="email0"
label='<%=AwardConstants.LABEL_EMAIL %>'
value="">
<aui:validator name="maxLength">100</aui:validator>
<aui:validator name="email"></aui:validator>
<aui:validator name="custom" errorMessage="fill-email">
function (val, fieldNode, ruleValue) {
var result = true;
var name = document.getElementById("<portlet:namespace/>name0").value;
if (name !== "" && val === "") {
result = false;
}
return result;
}
</aui:validator>
</aui:input>
</div>
</div>
</div>
After validating those fields and pressing the submit button goes to the next method:
public void saveAutofieldData(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, SystemException {
String groupworkIndexes = actionRequest.getParameter("groupworkIndexes");
_log.info("::::::::::::::::groupworkIndexes:::::::::::::::::::::::" + groupworkIndexes);
/**
* Split the row index by comma
*/
String[] indexOfRows = groupworkIndexes.split(",");
_log.info("::::::::::::::::indexOfRows.length:::::::::::::::::::::::"+ indexOfRows.length);
for (int i = 0; i < indexOfRows.length; i++) {
String name = (actionRequest.getParameter("name"+ indexOfRows[i])).trim();
String email = (actionRequest.getParameter("email"+ indexOfRows[i])).trim();
_log.info("::::::::::::Name::::::::::::::" + name);
_log.info("::::::::::::Email::::::::::::::" + email);
}
}
The problem is when It tries to read: actionRequest.getParameter("groupworkIndexes"); I get null.
Thank you in advance
I finally got the solution.
All examples I've seen it have been with "actionRequest" to retrieve the data:
String groupworkIndexes = actionRequest.getParameter("groupworkIndexes");
String name = actionRequest.getParameter("name" + indexOfRows[i]));
But in my case i've used the following lines:
String name = (uploadPortletRequest.getParameter("name" + indexOfRows[i]));
String groupworkIndexes = (uploadPortletRequest.getParameter("groupworkIndexes"));
Not always we would get the prefered values with actionRequest

Controlling cart with session

My cart is working fine in localhost but when i have hosted in cloud hosting it is not working well problem is that when i click add to cart button it will add one product with one quantity but when i add another product in the cart again it will override the previous one and show only one product in cart when i have added on last.. i don't know whats wrong with the sessions it will override the session again i guess. And another problem is that my my update cart button's functionalities and delete button functionalities in cart is not working it throw exception
Object reference not set to an instance of an object.
I have a controller name shoppingCartController here is the code
namespace Medi.Areas.User.Controllers
{
public class ShoppingCartController : Controller
{
ArrayList arr = new ArrayList();
int id;
BLL.IRepository<tbl_Product> de = new BLL.IRepository<tbl_Product>();
public ActionResult Index()
{
return View();
}
private int isExisting(int id)
{
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
if (cart[i].Pr.ProductID == id)
return i;
return -1;
}
public ActionResult Delete(int id)
{
int index = isExisting(id);
List<Items> cart = (List<Items>)Session["cart"];
cart.RemoveAt(index);
Session["cart"] = cart;
return PartialView("_pvCart");
}
public ActionResult OrderNow(string q)
{
if (Session["cart"] == null)
{
List<Items> cart = new List<Items>();
cart.Add(new Items(de.GetById(Convert.ToInt32(q)), 1));
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart,"Quantity","Quantity");
// cart[1]
}
else
{
id = Convert.ToInt32(q);
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity++;
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart, "Quantity", "Quantity");
}
return View("Cart");
}
[HttpPost]
public ActionResult UpdateCart(int[] ProductID,int [] quantity )
{
int[] x = new int[4];
int[] y = new int[4];
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
{
x[i] = ProductID[i];
y[i] = quantity[i];
updcart(x[i],y[i]);
}
Session["cart"] = cart;
return PartialView("_pvCart");
}
public void updcart(int id,int quantity) {
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity = quantity;
Session["cart"] = cart;
}
}
}
and here is the view name Cart.cshtml
#{
ViewBag.Title = "Cart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("UpdateCart", "ShoppingCart", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }))
{
#Html.AntiForgeryToken()
<br />
<br />
<div id="MyData">
#{Html.RenderPartial("_pvCart");}
</div>
<br /><br />
<input id="updatecart" type="submit" value="update Cart" />
}
and here is the partial view code
#using Medi.Models;
<script src="~/Scripts/metro.min.js"></script>
<table class="table hovered" cellpadding=" 2" cellspacing="2" border="1px">
<tr class="info">
<th></th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
#{
decimal s = 0;
}
#foreach (Items item in (List<Items>)Session["cart"])
{
<input id="ProductID" name="ProductID" type="hidden" value="#item.Pr.ProductID" />
s = s + (Convert.ToInt32(item.Pr.Price) * item.Quantity);
<tr>
<th>#Ajax.ActionLink("Delete", "Delete", new { id = item.Pr.ProductID }, new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }, new { #class = "mif-cross" })</th>
<td>#item.Pr.ProductName</td>
<td>#item.Pr.Price</td>
<td>
<input name="quantity" id="quantity" type="text" style="width:25px;" value="#item.Quantity" />
</td>
<td>#(item.Pr.Price * item.Quantity)</td>
</tr>
}
</table><br />
<hr />
<table cellpadding="1px" cellspacing="1px" style="float:right;">
<tr align="center" colspan="5" style="background-color:gray;">
<td><h3 style="padding:1px;">Total</h3></td>
<td> <h3 style="padding:1px;">Rs #s</h3></td>
</tr>
</table>
here is the model class
using BOL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Medi.Models
{
public class Items
{
tbl_Product pr = new tbl_Product();
public tbl_Product Pr
{
get { return pr; }
set { pr = value; }
}
int quantity;
public int Quantity { get; set; }
public Items()
{
}
public Items(tbl_Product product, int quantity)
{
this.Pr = product;
this.Quantity = quantity;
}
}
}
i have also write this code in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
<sessionState mode="InProc"/>

My Shopping Cart is not working as expected in ASP.NET MVC 5

My cart is working fine in localhost but when i have hosted in cloud hosting it is not working well problem is that when i click add to cart button it will add one product with one quantity but when i add another product in the cart again it will override the previous one and show only one product in cart when i have added on last.. i don't know whats wrong with the sessions it will override the session again i guess. And another problem is that my my update cart button's functionalities and delete button functionalities in cart is not working it throw exception
Object reference not set to an instance of an object.
I have a controller name shoppingCartController here is the code
namespace Medi.Areas.User.Controllers
{
public class ShoppingCartController : Controller
{
ArrayList arr = new ArrayList();
int id;
BLL.IRepository<tbl_Product> de = new BLL.IRepository<tbl_Product>();
public ActionResult Index()
{
return View();
}
private int isExisting(int id)
{
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
if (cart[i].Pr.ProductID == id)
return i;
return -1;
}
public ActionResult Delete(int id)
{
int index = isExisting(id);
List<Items> cart = (List<Items>)Session["cart"];
cart.RemoveAt(index);
Session["cart"] = cart;
return PartialView("_pvCart");
}
public ActionResult OrderNow(string q)
{
if (Session["cart"] == null)
{
List<Items> cart = new List<Items>();
cart.Add(new Items(de.GetById(Convert.ToInt32(q)), 1));
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart,"Quantity","Quantity");
// cart[1]
}
else
{
id = Convert.ToInt32(q);
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity++;
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart, "Quantity", "Quantity");
}
return View("Cart");
}
[HttpPost]
public ActionResult UpdateCart(int[] ProductID,int [] quantity )
{
int[] x = new int[4];
int[] y = new int[4];
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
{
x[i] = ProductID[i];
y[i] = quantity[i];
updcart(x[i],y[i]);
}
Session["cart"] = cart;
return PartialView("_pvCart");
}
public void updcart(int id,int quantity) {
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity = quantity;
Session["cart"] = cart;
}
}
}
and here is the view name Cart.cshtml
#{
ViewBag.Title = "Cart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("UpdateCart", "ShoppingCart", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }))
{
#Html.AntiForgeryToken()
<br />
<br />
<div id="MyData">
#{Html.RenderPartial("_pvCart");}
and here is the partial view code
#using Medi.Models;
<script src="~/Scripts/metro.min.js"></script>
<table class="table hovered" cellpadding=" 2" cellspacing="2" border="1px">
<tr class="info">
<th></th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
#{
decimal s = 0;
}
#foreach (Items item in (List<Items>)Session["cart"])
{
<input id="ProductID" name="ProductID" type="hidden" value="#item.Pr.ProductID" />
s = s + (Convert.ToInt32(item.Pr.Price) * item.Quantity);
<tr>
<th>#Ajax.ActionLink("Delete", "Delete", new { id = item.Pr.ProductID }, new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }, new { #class = "mif-cross" })</th>
<td>#item.Pr.ProductName</td>
<td>#item.Pr.Price</td>
<td>
<input name="quantity" id="quantity" type="text" style="width:25px;" value="#item.Quantity" />
</td>
<td>#(item.Pr.Price * item.Quantity)</td>
</tr>
}
</table><br />
<hr />
<table cellpadding="1px" cellspacing="1px" style="float:right;">
<tr align="center" colspan="5" style="background-color:gray;">
<td><h3 style="padding:1px;">Total</h3></td>
<td> <h3 style="padding:1px;">Rs #s</h3></td>
</tr>
</table>
here is the model class
using BOL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Medi.Models
{
public class Items
{
tbl_Product pr = new tbl_Product();
public tbl_Product Pr
{
get { return pr; }
set { pr = value; }
}
int quantity;
public int Quantity { get; set; }
public Items()
{
}
public Items(tbl_Product product, int quantity)
{
this.Pr = product;
this.Quantity = quantity;
}
}
}
i have also write this code in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
<sessionState mode="InProc"/>

Model is getting null on post on Child Partial View MVC5

I asked this question in a another thread but i never got the answer. Hope someone bright can help me with this.
Basically what i'm trying is to get TestModel back to ActionResult Questions(TestModel test, FormCollection formCollection). Whenever next button is pressed in _Question.cshtml partial View ActionResult Index(TestModel test) is bounded with empty model therefore i can't get anything from user to fill my testModel. Please Help
///////////////Models//////////////
[Serializable]
public class TestModel
{
private QuestionModel _currenQuestionModel;
public int TestID { get; set; }
public string TestName { get; set; }
public string Instructions { get; set; }
public double TestTime { get; set; }
public QuestionModel CurrenQuestionModel
{
get
{
if (_currenQuestionModel == null &&
Questions != null &&
Questions.Count > 0)
_currenQuestionModel = Questions.First();
return _currenQuestionModel;
}
set { _currenQuestionModel = value; }
}
public List<QuestionModel> Questions { get; set; }
}
public class QuestionModel
{
public int QuestionID { get; set; }
public string Question { get; set; }
public bool HasMultipleAnswers { get; set; }
public IList<PossibleAnswerModel> PossibleAnswers { get; set; }
}
public class PossibleAnswerModel
{
public bool IsSelected { get; set; }
public string DisplayText { get; set; }
}
}
////////////////// Controller /////////////////
public class TestController : Controller
{
public ActionResult Index(int id)
{
var model = _testColletion.FirstOrDefault(r => r.TestID == id);
return View(model);
}
[HttpPost]
public ActionResult Index(TestModel test)
{
//var model = (TestModel) Session["CurrentTest"];
return View(test);
}
[ChildActionOnly]
[HttpGet]
public ActionResult Questions(TestModel test)
{
var testModel = _testColletion.Single(r => r.TestID == test.TestID);
return PartialView("_Start", testModel);
}
[HttpPost]
public ActionResult Questions(TestModel test, FormCollection formCollection)
{
var q = formCollection.Count >2 ? formCollection.GetValues(1):null;
var testModel = _testColletion.FirstOrDefault(r => r.TestID == test.TestID);
//if (questionID == 0)
//{
// testModel.CurrenQuestionModel = testModel.Questions.First();
//}
if (!string.IsNullOrWhiteSpace(Request["next"]))
{
var nextQuestionIndex =
testModel.Questions.FindIndex(r => r.QuestionID == testModel.CurrenQuestionModel.QuestionID) + 1;
testModel.CurrenQuestionModel = testModel.Questions[nextQuestionIndex];
}
else if (!string.IsNullOrWhiteSpace(Request["prev"]))
{
var prevQuestionIndex =
testModel.Questions.FindIndex(r => r.QuestionID == testModel.CurrenQuestionModel.QuestionID) - 1;
testModel.CurrenQuestionModel = testModel.Questions[prevQuestionIndex];
}
return PartialView("_Question", testModel);
}
private static List<TestModel> _testColletion = new List<TestModel>()
{
new TestModel()
{
TestID = 1,
TestName = "ASP.NET",
Instructions = "Please choose from appropriate options",
TestTime = 2.40,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, Question = "Question 1"}
}
},
new TestModel()
{
TestID = 2,
TestName = "ASP.NET MVC",
Instructions = "Please choose from appropriate options",
TestTime = 1.00,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, HasMultipleAnswers=true, Question = "Question 1", PossibleAnswers = new List<PossibleAnswerModel>()
{
new PossibleAnswerModel(){DisplayText = "Possible Answer 1"},
new PossibleAnswerModel(){DisplayText = "Possible Answer 2"},
new PossibleAnswerModel(){DisplayText = "Possible Answer 3"},
new PossibleAnswerModel(){DisplayText = "Possible Answer 4"},
}},
new QuestionModel(){QuestionID = 2, HasMultipleAnswers=true, Question = "Question 2"},
new QuestionModel(){QuestionID = 3, HasMultipleAnswers=true, Question = "Question 3"},
new QuestionModel(){QuestionID = 4, HasMultipleAnswers=true, Question = "Question 4"},
new QuestionModel(){QuestionID = 5, HasMultipleAnswers=true, Question = "Question 5"},
}
},
new TestModel()
{
TestID = 3,
TestName = "ASP.NET Spring",
Instructions = "Please choose from appropriate options",
TestTime = 1.00,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, Question = "Question 1"},
new QuestionModel(){QuestionID = 2, Question = "Question 2"},
new QuestionModel(){QuestionID = 3, Question = "Question 3"},
new QuestionModel(){QuestionID = 4, Question = "Question 4"},
}
},
new TestModel()
{
TestID = 4,
TestName = ".NET C#",
Instructions = "Please choose from appropriate options",
TestTime = 4.40,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, Question = "Question 1"},
new QuestionModel(){QuestionID = 2, Question = "Question 2"}
}
}
};
}
/////////// Inside _Question.cshtml partial view///////////////
#model InterviewQ.MVC.Models.TestModel
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#*#Html.HiddenFor(r => r.CurrentQuestionID)*#
<div>
<br />
<h4>Question #Model.CurrenQuestionModel.QuestionID</h4>
<hr />
<p>#Model.CurrenQuestionModel.Question</p>
</div>
<p>
#if (Model.CurrenQuestionModel.HasMultipleAnswers)
{
#Html.Partial("_MultipleAnswerQuestionView", Model.CurrenQuestionModel)
}
</p>
<p>
#if (Model.CurrenQuestionModel.QuestionID > 0 && Model.CurrenQuestionModel.QuestionID < Model.Questions.Count)
{
if (Model.CurrenQuestionModel.QuestionID > 1)
{
<input type="submit" class="btn btn-default" value="Previous" name="prev" />
}
<input type="submit" class="btn btn-default" value="Next" name="next" />
}
#if (Model.CurrenQuestionModel.QuestionID == Model.Questions.Count)
{
<input type="submit" class="btn btn-default" value="Finish" name="finish" />
}
</p>
}
//////////// Inside _MultipleAnswerQuestionView.cshtml partial view///////////////
#model InterviewQ.MVC.Models.TestModel
#if (!Model.CurrenQuestionModel.HasMultipleAnswers)
{
throw new InvalidOperationException("This answer optioin template doesn't support this type of questions");
}
#for (var i = 0; i < Model.CurrenQuestionModel.PossibleAnswers.Count; i++)
{
<div class="row">
<div class="col-lg-6">
<div class="input-group">
<span class="input-group-addon">
#Html.CheckBoxFor(r => r.CurrenQuestionModel.PossibleAnswers[i].IsSelected)
#*<input type="checkbox" value="#Model.CurrenQuestionModel.PossibleAnswers[i].IsSelected" name="#Model.CurrenQuestionModel.PossibleAnswers[i].IsSelected">*#
</span>
<p>
#Model.CurrenQuestionModel.PossibleAnswers[i].DisplayText
</p>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
}

How to call SP.UI.Status in visual webpart

I have a scenario where i need to display an Alert banner with the title column in my list.
Below is the code which iam trying to use . But it is not displaying correctly. Can any one let me know Errorl
<script type="text/ecmascript" language="ecmascript">
var strStatusID;
function showInfo(strMessage) {
alert("Code sucess");
strStatusID = SP.UI.Status.addStatus(strMessage, true);
alert(strMessage.toString());
SP.UI.Status.setStatusPriColor(strStatusID, "yellow");
}
</script>
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="lblScripter" runat="server" Visible="false"></asp:Label>
</asp:Panel>
public void LoadGrid()
{
//System.Diagnostics.Debugger.Break();
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Neq><FieldRef Name='NoOfDays' /><Value Type='Calculated'>0:00</Value></Neq></Where>";
SPListItemCollection _AlertListCollection = oSpList.GetItems(oQuery);
DataTable Table_Calendar = _AlertListCollection.GetDataTable();
if (Table_Calendar != null)
{
foreach (SPListItem item in _AlertListCollection)
{
MessageShow = item["Title"].ToString();
}
// strStatusID = SP.UI.Status.addStatus(strMessage, true);
lblScripter.Text = "<Script language='javascript;>showInfo('" + MessageShow + "');</script>";
}
else
{
lblScripter.Visible = false;
}
}
<asp:Timer runat="server" ID="UpdateTimer" Interval="6000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="DateStampLabel" />
<asp:Label ID="lblScripter" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
System.Diagnostics.Debugger.Break();
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["Alertlist"];
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Neq><FieldRef Name='NoOfDays' /><Value Type='Calculated'>0:00</Value></Neq></Where>";
SPListItemCollection _AlertListCollection = oSpList.GetItems(oQuery);
DataTable Table_Calendar = _AlertListCollection.GetDataTable();
if (Table_Calendar != null)
{
foreach (SPListItem item in _AlertListCollection)
{
MessageShow = item["Title"].ToString();
Enddate = DateTime.Parse(item["EndDate"].ToString());
}
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {showInfo('" + MessageShow + "');}, 'sp.js');</script>";
if (Currenttime >= Enddate)
{
lblScripter.Text = "hi after date tim refreshed";
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {removeAllInfos();}, 'sp.js');</script>";
}
}
//else
//{
// lblScripter.Visible = false;
//}
}
Try to set :
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {showInfo('" + MessageShow + "');}, 'sp.js');</script>"
Most likely this will solve your problem of calling the SP.UI.Status javascript functions before they have been loaded.
I Have solved this PFB code in order to acheive this. Thanks to my friend Hameed who has helped me to acheive the same
<script type="text/ecmascript" language="ecmascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RegisterMethods);
function RegisterMethods() {
showInfo();
RemoveLastStatus();
}
function showInfo() {
var strMessage = document.getElementById('<%= Message.ClientID %>').value;
var strstatus = document.getElementById('<%= StartStatus.ClientID %>').value;
if (strMessage != null) {
if (strstatus != "false") {
var strStatusID;
strStatusID = SP.UI.Status.addStatus(strMessage);
SP.UI.Status.setStatusPriColor(strStatusID, "red");
document.getElementById('<%= StartStatus.ClientID %>').value = "false";
document.getElementById('<%= StatusId.ClientID %>').value = strStatusID;
}
}
}
function RemoveLastStatus() {
var statusId = document.getElementById('<%= StatusId.ClientID %>').value;
var stopStatus = document.getElementById('<%= StopStatus.ClientID %>').value;
if (statusId != null) {
if (stopStatus == "true") {
SP.UI.Status.removeStatus(statusId);
statusId = '';
}
}
}
</script>
<asp:Timer runat="server" ID="UpdateTimer" Interval="5000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="DateStampLabel" />
<asp:Label ID="lblScripter" runat="server" Visible="True"></asp:Label>
<asp:HiddenField ID="StartStatus" runat="server" />
<asp:HiddenField ID="StopStatus" runat="server" />
<asp:HiddenField ID="Message" runat="server" />
<asp:HiddenField ID="StatusId" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
CODEBEHIND.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Globalization;
using System.Data;
using System.Linq;
using Microsoft.SharePoint.Utilities;
namespace ITBANNER
{
public partial class ITOpsBannerUserControl : UserControl
{
String MessageShow = string.Empty;
DateTime Enddate, starttime;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPListItemCollection items = oSpList.Items;
SPListItem item;
for (int i = 0; i < items.Count; i++)
{
item = items[i];
Console.WriteLine("Index = {0} ID = {1}", i, item.ID);
}
SPListItem item = oSpList.GetItemById(3);
Message.Value = item["Title"].ToString();
starttime = DateTime.Parse(item["StartDate"].ToString());
if (Currenttime >= starttime)
{
StartStatus.Value = "true";
StopStatus.Value = "false";
}
}
}
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPListItem item = oSpList.GetItemById(3);
Enddate = DateTime.Parse(item["EndDate"].ToString());
if (Currenttime >= Enddate)
{
StopStatus.Value = "true";
}
}
//public void HideStatusBar()
//{
// string script = "document.onreadystatechange=fnRemoveAllStatus; function fnRemoveAllStatus(){removeAllStatus(true)};";
// this.Page.ClientScript.RegisterClientScriptBlock(typeof(Type), "statusBarRemover", script, true);
//}
}
}

Resources