Passing Data Between Current and Subsequent Request-MVC

Use TempData instead of ViewData/ViewBag to store data that should persist after redirect. ViewData/ViewBag allow to pass value from controller to view.

You can use TempData.You can pass every types of data between to action, whether they are in same controller or not. Your code should be something like it:

 public ActionResult GetMDN(string msisdn)
    {
        int sngid=10;

        TempData["ID"] = sngid;

        return RedirectToAction("IIndex");
    }

    public ActionResult IIndex()
    {

        int id = Convert.ToInt32(TempData["ID"]);// id will be 10;
    }

ASP.NET MVC offers us three options – ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Let’s discuss or get key points on those three objects:

Similarities between ViewBag & ViewData:

  1. Helps to maintain data when you move from controller to view.
  2. Used to pass data from controller to corresponding view.
  3. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

  1. ViewData is a dictionary of objects that is derived from ViewDataDictionary class and is accessible using strings as keys.
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  3. ViewData requires typecasting for complex data type and check for null values to avoid error.
  4. ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:

public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}
public ActionResult Index()
{
    ViewData["Name"] = "Monjurul Habib";
    return View();
}

In View:

@ViewBag.Name 
@ViewData["Name"]

TempData:

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is the life cycle of the object. TempData keeps the information for the time of an HTTP Request. This mean only from one page to another. This also works with a 302/303 redirection because it’s in the same HTTP Request. It helps to maintain data when you move from one controller to other controller or from one action to other action. In other words, when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is used when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. It is generally used to store only one time messages like error messages, validation messages.

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}
public ActionResult About() 
{     
    var model= TempData["ModelName"];     
    return View(model); 
}

The last mechanism is the Session which works like the ViewData, like a Dictionary that takes a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also needs more verification to never have any confidential information. Regarding ViewData or ViewBag, you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular ASP.NET MVC request. You can use ViewData/ViewBag in your child action, but be careful that you are not using it to populate the unrelated data which can pollute your controller.


		
Advertisements

Page loading in update panel

<%–
<“div style=”position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;”>
<“span style=”border-width: 0px; position: fixed; padding: 50px; background-color: #000000; font-size: 36px; left: 40%; top: 40%;”>
<“img alt=”” height=”10px” width=”20px” src=”../images/loader.gif” style=”width: 91%; height: 18%;”>

 

–%>

Gridview Add update delete

*******ASPX page Coding*********

<asp:GridView ID=”grdInspectionMap” runat=”server” BorderWidth=”1px” AutoGenerateColumns=”false”
AllowSorting=”true” BackColor=”White” CssClass=”summary” BorderStyle=”Solid”
BorderColor=”#009955″ CellPadding=”2″ CellSpacing=”2″ DataKeyNames=”DivisionId”
AllowPaging=”True” PageSize=”20″ OnPageIndexChanging=”grdInspectionMap_PageIndexChanging”
OnRowCreated=”grdInspectionMap_RowCreated” OnRowCancelingEdit=”grdInspectionMap_RowCancelingEdit”
OnRowDeleting=”grdInspectionMap_RowDeleting” OnRowEditing=”grdInspectionMap_RowEditing”
OnRowUpdating=”grdInspectionMap_RowUpdating”>
<PagerTemplate>
<table width=”100%”>
<tr>
<td align=”right”>
<font color=”black”>Goto Page</font>
<asp:DropDownList ID=”ddlInspectionPageSelector” runat=”server” AutoPostBack=”true”
OnSelectedIndexChanged=”ddlInspectionPageSelector_SelectedIndexChanged”>
</asp:DropDownList>
<asp:Button Text=”First” CommandName=”Page” CssClass=”inputButton” CommandArgument=”First”
runat=”server” ID=”btnFirst” />
<asp:Button Text=”Previous” CommandName=”Page” CssClass=”inputButton” CommandArgument=”Prev”
runat=”server” ID=”btnPrevious” />
<asp:Button Text=”Next” CommandName=”Page” CssClass=”inputButton” CommandArgument=”Next”
runat=”server” ID=”btnNext” />
<asp:Button Text=”Last” CommandName=”Page” CssClass=”inputButton” CommandArgument=”Last”
runat=”server” ID=”btnLast” />
</td>
</tr>
</table>
</PagerTemplate>
<Columns>
<asp:TemplateField HeaderText=”SNO”>
<ItemTemplate>
<%# Container.DataItemIndex +1 %>
</ItemTemplate>
<ItemStyle Width=”10px” />
</asp:TemplateField>
<asp:TemplateField HeaderText=”ID” Visible=”false”>
<ItemTemplate>
<asp:Label ID=”lblInspectionQuestion” runat=”server” Text='<%# Bind(“DivisionId”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Division Name”>
<ItemTemplate>
<asp:Label ID=”lblName” runat=”server” Text='<%# Bind(“Name”) %>’></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID=”txtName” Text='<%# Bind(“Name”) %>’
runat=”server”></asp:TextBox>
<asp:RequiredFieldValidator ID=”rfvInspectionQuestion1″ runat=”server” ControlToValidate=”txtName”
Display=”None” ValidationGroup=”Edit_Inspection”></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtName_F” runat=”server”></asp:TextBox>
<asp:RequiredFieldValidator ID=”rfvInspectionQuestion2″ runat=”server” ControlToValidate=”txtName_F”
Display=”None” ValidationGroup=”Add_Inspection”></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Action”>
<ItemTemplate>
<asp:LinkButton ID=”btnEdit” Text=”Edit” runat=”server” CausesValidation=”true” CommandName=”Edit”
Visible='<%#(Convert.ToBoolean(Eval(“DivisionId”))) %>’ />&nbsp;&nbsp;
<asp:LinkButton ID=”btnDelete” Text=”Delete” runat=”server” Visible='<%#(Convert.ToBoolean(Eval(“DivisionId”))) %>’
CommandName=”Delete” />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID=”btnUpdate” Text=”Update” runat=”server” CommandName=”Update”
ValidationGroup=”Edit_Inspection” />
<asp:LinkButton ID=”btnCancel” Text=”Cancel” runat=”server” CommandName=”Cancel” />
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID=”btnSave” runat=”server” ValidationGroup=”Add_Inspection” CausesValidation=”True”
OnCommand=”btnAddFeedback_Click” CommandName=”Save” Text=”Save” ForeColor=”#FF0000″></asp:LinkButton>
&nbsp;<asp:LinkButton ID=”btnCancel” runat=”server” CausesValidation=”False” OnCommand=”btnAddFeedback_Click”
CommandName=”Cancel” Text=”Cancel” ForeColor=”#FF0000″></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle ForeColor=”#8C4510″ BackColor=”#F7DFB5″></FooterStyle>
<PagerStyle ForeColor=”#8C4510″ HorizontalAlign=”right”></PagerStyle>
<HeaderStyle ForeColor=”black” BackColor=”#ffcc99″></HeaderStyle>
<RowStyle BackColor=”#f5f5f5″ />
<AlternatingRowStyle BackColor=”#ffffff” />
<PagerSettings FirstPageText=”First” LastPageText=”Last” Mode=”NextPreviousFirstLast”
NextPageText=”Next” PreviousPageText=”Previous” Position=”Top” />
</asp:GridView>

 

************CS Page Coding************

GridViewRow AddNewGridRow;
private void BindGrid()
{
try
{
var InspectionQuestionData = sidb.Divisions.Select(_ => new clsDesignation { DivisionID = _.DivisionId, Name = _.DivisionName}).ToList();
if (InspectionQuestionData.Any())
{
grdInspectionMap.DataSource = InspectionQuestionData;
grdInspectionMap.DataBind();
}
else
{
dt = new DataTable();
dt.Columns.Add(“DivisionID”);
dt.Columns.Add(“Name”, typeof(String));
dt.Rows.Add(dt.NewRow());
dt.Rows[0][0] = “false”;
dt.Rows[0][1] = “NO RESULT FOUND!”;
grdInspectionMap.DataSource = dt;
grdInspectionMap.DataBind();
}
}
catch (Exception ex)
{
(new MailClass()).SendErrorMail(ex, “ADMIN_InstectionFormMapping::BindGrid”);
}
}

protected void grdInspectionMap_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdInspectionMap.EditIndex = -1;
grdInspectionMap.PageIndex = e.NewPageIndex;
BindGrid();
}

protected void grdInspectionMap_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
SetPagerButtonStates(grdInspectionMap, e.Row, this, “ddlInspectionPageSelector”);
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
int DivisionId = 0;
if (int.TryParse(Convert.ToString(grdInspectionMap.DataKeys[e.Row.RowIndex].Values[“DivisionId”]), out DivisionId))
{

}
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
AddNewGridRow = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell th = new TableHeaderCell();
th.ColumnSpan = e.Row.Cells.Count;
if (grdInspectionMap.EditIndex == -1)
{
th.HorizontalAlign = HorizontalAlign.Right;
LinkButton btnAddNew = new LinkButton();
btnAddNew.Text = “Add New”;
btnAddNew.ForeColor = System.Drawing.Color.Red;
btnAddNew.Command += new CommandEventHandler(btnAddFeedback_Click);
btnAddNew.CommandName = “AddNew”;
th.Controls.Add(btnAddNew);
}
AddNewGridRow.Cells.Add(th);
grdInspectionMap.Controls[0].Controls.Add(AddNewGridRow);
e.Row.BackColor = grdInspectionMap.FooterStyle.BackColor;
e.Row.Font.Bold = true;
}

}
protected void ddlInspectionPageSelector_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlPageSelector = (DropDownList)grdInspectionMap.TopPagerRow.FindControl(“ddlInspectionPageSelector”);
grdInspectionMap.PageIndex = ddlPageSelector.SelectedIndex;
BindGrid();
}

protected void grdInspectionMap_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
GridViewRow row = (GridViewRow)grdInspectionMap.Rows[e.RowIndex];
int RowID = Convert.ToInt32(grdInspectionMap.DataKeys[e.RowIndex].Values[“DivisionId”].ToString());
var DeleteInspectionOption = sidb.Divisions.Where(_ => _.DivisionId.Equals(RowID)).ToList();
if (DeleteInspectionOption.Any())
{
sidb.Divisions.DeleteAllOnSubmit(DeleteInspectionOption);
sidb.SubmitChanges();
}
grdInspectionMap.EditIndex = -1;
BindGrid();
}
catch (Exception ex)
{
(new MailClass()).SendErrorMail(ex, “ADMIN_InstectionFormMapping::grdInspectionMap_RowDeleting”);
}
}

protected void grdInspectionMap_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int DivisionId = Convert.ToInt32(grdInspectionMap.DataKeys[e.RowIndex].Values[“DivisionId”].ToString());
string txtName = ((TextBox)grdInspectionMap.Rows[e.RowIndex].FindControl(“txtName”)).Text.Trim();

var EditableInspectionQuestion = sidb.Divisions.Where(_ => _.DivisionId.Equals(DivisionId)).SingleOrDefault();
if (EditableInspectionQuestion != null)
{
EditableInspectionQuestion.DivisionName = txtName;
sidb.SubmitChanges();
}

grdInspectionMap.EditIndex = -1;
BindGrid();
}
protected void grdInspectionMap_RowEditing(object sender, GridViewEditEventArgs e)
{
grdInspectionMap.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdInspectionMap_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdInspectionMap.EditIndex = -1;
BindGrid();
}

protected void btnAddFeedback_Click(object sender, CommandEventArgs e)
{
if (e.CommandName == “AddNew”)
{
BindGrid();
grdInspectionMap.FooterRow.Visible = true;
AddNewGridRow.Visible = false;
}
else if (e.CommandName == “Save”)
{
InsertNewFeedBackMapping((TableRow)grdInspectionMap.FooterRow);
}
}

private void InsertNewFeedBackMapping(TableRow htmlTableRow)
{

string txtName = ((TextBox)htmlTableRow.FindControl(“txtName_F”)).Text.Trim();

Division obj = new Division();
obj.DivisionName = txtName;
sidb.Divisions.InsertOnSubmit(obj);
sidb.SubmitChanges();
grdInspectionMap.EditIndex = -1;
BindGrid();
}

 

private void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page, String DropDownName)
{
int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
Button btnFirst = (Button)gvPagerRow.FindControl(“btnFirst”);
Button btnPrevious = (Button)gvPagerRow.FindControl(“btnPrevious”);
Button btnNext = (Button)gvPagerRow.FindControl(“btnNext”);
Button btnLast = (Button)gvPagerRow.FindControl(“btnLast”);
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount – 1));
DropDownList ddlPageSelector = (DropDownList)gvPagerRow.FindControl(DropDownName);
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++)
{
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
}

class clsDesignation
{
public int DivisionID { get; set; }
public string Name { get; set; }
}