Telerik MVC grid Access Data out side the grid binding - asp.net-mvc-3

In Telerik MVC 3.0 Grid (Razor engine)
How can i access the data after grid binding.
I am using Detailed view tab
using below code.
items.Add()
.Text("Additional Tab")
.Content(#<text>
#(Html.Telerik()
.Grid<Models.PModel>()
.Name( "Additional_<#= AddressID #>" )
.DataBinding( dataBinding => dataBinding.Ajax()
.Select( "Action", "Controller", new { ID = "<#= ID #>" } ) )
.Pageable()
.Sortable()
.Columns( columns =>
{
columns.Bound( e => e.Name ).Title( "Name" ).Width( 150 );
columns.Bound( e => e.Email ).Title( "Email" );
columns.Bound( e => e.Status ).Title( "Prescriber Status" );
columns.Template( e => e.ID ).ClientTemplate(
Ajax.ActionLink( "Edit", "EditDetails", new { ID = "<#= ID #>", PID = "<#= PID #>" },
new AjaxOptions
{
OnSuccess = "LoadAddEditForm",
UpdateTargetId = "ShowAddEditFormDialogModel",
InsertionMode = InsertionMode.Replace
},
new { #class = "button" } ).ToString() );
} )
.NoRecordsTemplate( "No additional added for this" )
)
#Ajax.ActionLink("Add New", "AddEdit", "Controller",
new { ID = "<#= ID #>"},
new AjaxOptions
{
OnSuccess = "LoadAddEditForm",
UpdateTargetId = "ShowAddEditFormDialogModel",
InsertionMode = InsertionMode.Replace
},
new { #class = "button", id="AjaxAddNewButton" })
</text>);
Now the Problem is,, if you notice i have added a Ajax.Action link after the grid binding.
#Ajax.ActionLink("Add New", "AddEdit", "Controller",
new { ID = "<#= ID #>"},
new AjaxOptions
{
OnSuccess = "LoadAddEditForm",
UpdateTargetId = "ShowAddEditFormDialogModel",
InsertionMode = InsertionMode.Replace
},
new { #class = "button", id="AjaxAddNewButton" })
In this Ajax Link I can get the value of object new { ID = "<#= ID #>"}
as I am trying to access the <#= ID #> after the grid binding, it is not rendering the value.
How can i get this work?
Any help would be greatly appreciated.
Thanks

This is not possible.
The <# ID #> you are using is for a single row in your grid. It cannot be used outside the .Columns() method. So your column template may work, but if you inspect what is being sent to the Action handling the binding, you will see that the ID parameter literally equals "<# ID #>".
For the ActionLink past the grid, what ID did you want? from which row?

Related

PagedList.MVC with EnableUnobtrusiveAjaxReplacing and other render option

I've got pager like this:
#Html.PagedListPager(Model.komentarzeListModeracja, page =>
Url.Action("ModeracjaKomentarze", new {
DotyczyID = Model.DotyczyID, page
}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() {
HttpMethod = "Get", UpdateTargetId = "ModeracjaUpdate1"
}))
Could You tell me how can I add other render option to this ?. Is it possible ?.
There are already several versions\flavors incorporated into the class (intellisense enabled: Classic to OnlyShowFivePagesAtATime, Minimal and Bootstrap, etc.).
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(PagedListRenderOptions.TwitterBootstrapPagerAligned, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "divpagedlist" }))
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(PagedListRenderOptions.ClassicPlusFirstAndLast, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "divpagedlist" }))
Simply, comma separated properties for the class.
A good reference at this time for PagedListRenderOptions (Class) properties:
http://www.nudoq.org/#!/Packages/PagedList.Mvc/PagedList.Mvc/PagedListRenderOptions
(please note this site is beta, cannot be sure how long link will be valid)
Another way...
#Html.PagedListPager(Model, page => Url.Action("FileIndex",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions()
{
DisplayLinkToLastPage = PagedListDisplayMode.IfNeeded,
DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded,
Display = PagedListDisplayMode.IfNeeded,
LiElementClasses = new List<string> { "myClass", "yourClass" },
MaximumPageNumbersToDisplay = 10
}, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "fileListTable" }))

Clickable image in WebGrid inside a Controller (via Ajax )?

I'm using the MVC3 WebGrid inside my controller.I need to have an image in a column,such that when you click on that image, data is passed to an action inside any controller.I want to do this via Ajax, i.e. clicking on the image shouldn't cause a post back,it should be an Ajax call to an Action on some Controller.And I would like to pass an object (model), not any string,or int, or whatever).
public ActionResult AddInGrid(AjaxModel m)
{
if (Session["ajaxmodel"] == null)
{
Session.Add("ajaxmodel", a.am);
}
List<AjaxModel> list = (List<AjaxModel>)Session["ajaxmodel"];
list.Insert(0, m);
Session.Add("ajaxmodel", list);
WebGrid g = new WebGrid(list);
IHtmlString s = g.GetHtml();
string s1 = s.ToString();
return Json(new { text = s1 });
}
What should be put inside of GetHtml() method??
EDIT: Here's what I've tried so far, and it isn't working:
I've found out what HTML renders on Ajax.ActionLink and tried to incorporate that
WebGrid g = new WebGrid(list);
string link = string.Format(#"<a data-ajax='true' data-ajax-method='GET' data-ajax-mode='replace' href='/Home/Delete/{0}' />Delete</a>",item.fname);
IHtmlString s = g.GetHtml(g.Columns(g.Column(format:link)));
#grid.GetHtml(
columns: grid.Columns(
grid.Column(
columnName: "",
format:
#<text>
#Ajax.ActionLink(
"Delete",
"delete",
"home",
new AjaxOptions {
UpdateTargetId = "sometargetdiv",
InsertionMode = InsertionMode.Replace
}
)
</text>
)
)
)
As far as passing an entire model to the action is concerned, well, you could use the routeValues parameter and pass the different properties as query string parameters:
#Ajax.ActionLink(
"Delete",
"delete",
"home",
new {
fname = item.fname,
lname = item.lname
.... and so on for each property you want to fetch back
},
new AjaxOptions {
UpdateTargetId = "sometargetdiv",
InsertionMode = InsertionMode.Replace
}
)

ASP.NET MVC - Current Selected value doesnt get selected in IE

In my Action for Editing an item in my model I have:
ViewBag.PossibleSource = context.Source.ToList();
In my View I have:
#Html.DropDownListFor(model => model.SourceID, ((IEnumerable<btn_intranet.Areas.DayBook.Models.DayBookSource>)ViewBag.PossibleSource).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.SourceName),
Value = option.SourceID.ToString(),
Selected = (Model != null) && (option.SourceID == Model.SourceID)
}))
In Chrome this works as expected. When I pass a model to my view, the current value that's set in my model is the selected value in the list. But in IE8 and 9 it's selected value is the ORIGINAL value my model was set as even though the update does work. So if I selected "hello" originally and then edited to "world". In chrome when i reload the page it will be set to "world" but in IE "hello" is selected in the dropdown even tho "world" is set in my database for my model. It is worth noting these are updated via AJAX
EDIT:
Ajax.Actionlink:
#Ajax.ActionLink(item.ItemNumber, "EditItem", new { id = item.QuoteLineID, enquiryId = item.EnquiryID }, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "EditItem"
})
This loads the form onto the view.
Ajax.BeginForm:
#using (Ajax.BeginForm("EditItem", new { controller = "QuoteLines" }, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "Summary"
}, new { #class = "manual-search cf" }))
{
...Other Model inputs
#Html.DropDownListFor(model => model.SourceID, ((IEnumerable<btn_intranet.Areas.DayBook.Models.DayBookSource>)ViewBag.PossibleSource).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.SourceName),
Value = option.SourceID.ToString(),
Selected = (Model != null) && (option.SourceID == Model.SourceID)
}))
<input type="submit" class="update-items" value="Update Line" />
}
EditItem Action GET request:
public virtual ActionResult EditItem(int id)
{
try
{
DayBookQuoteLines q = context.QuoteLines.Single(x => x.QuoteLineID == id);
ViewBag.PossibleSource = context.Source.ToList();
if (Request.IsAjaxRequest())
{
return PartialView("_EditItem", q);
}
else
{
return RedirectToAction("SalesDetails", new { controller = "Enquiries", id = q.EnquiryID });
}
}
catch (Exception ex)
{
return PartialView("_Error", ex.Message);
}
}
EditItem Action POST request:
[HttpPost]
public virtual ActionResult EditItem(DayBookQuoteLines q)
{
try
{
ViewBag.PossibleSource = context.Source.ToList();
if (ModelState.IsValid)
{
context.Entry(q).State = EntityState.Modified;
context.SaveChanges();
return PartialView("_GetSummary", context.Vehicles.Where(x => x.EnquiryID == q.EnquiryID).ToList());
}
return PartialView("_EditItem", q);
}
catch (Exception ex)
{
return PartialView("_Error", ex.Message);
}
}
I've fixed it, I renamed my GET request for EditItem to EditItemGet and then in my #Ajax.ActionLink I did:
#Ajax.ActionLink(item.ItemNumber, "EditItemGet", new { id = item.QuoteLineID, enquiryId = item.EnquiryID }, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "EditItem",
HttpMethod = "POST"
})
It was a Cache issue. Thats why it only failed in IE which likes Cache. I read before that making the request a POST request prevents Caching.

Passing routeValues to Controller in MVC 3

i have this code in View
#using (Html.BeginForm())
{
#: Location #Html.DropDownList("territryID", (SelectList)ViewBag.Territory, "choose one")
#Ajax.ActionLink(
"ok",
"Info", new { territryID = "#territryID" },
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "post1"
})
<div id="post1">
</div>
}
and this code in my Controller
[HttpPost]
public ActionResult Info(int? territryID)
{
if (territryID == null)
{
return RedirectToAction("Info");
}
var model = (from c in _db.OCRDs
where c.Territory == territryID
select c).Distinct();
return PartialView("_getCustomerByTerritory", model);
}
how to passing my dropdownlist selected value to territryID parameter in controller, how to do that?
thanks,
erick
How about this, initialize your URL to something like this (also note the assignment of an id to the link):
#Ajax.ActionLink("ok", "Info", new { territryID = "REPLACEME" }, new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", UpdateTargetId = "post1" }, new { id = "oklink" })
Replace the placeholder (REPLACEME) when the dropdown changes, like so:
<script>
$('#territryID').change(function () {
var newid = $('#territryID').val();
var oldLink = $('#oklink').attr('href');
var newLink = oldLink.replace('REPLACEME', newid);
$('#oklink').attr('href', newLink);
});
</script>

Hiding columns values for few records in the grid depending on their role type: MVC3

**I am trying to create a view which has a grid
View layout, I am using is:**
#model IEnumerable<VC.MC.ReportalWeb.UI.Users>
#using myspace
#{
ViewBag.Title = "Users";
var grid = new WebGrid(source: Model, canSort: true);
}
<h2>Users</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
#grid.GetHtml(columns: grid.Columns(
grid.Column("UserName"),
grid.Column("Email"),
grid.Column(
header: "",
style: "text-align-center",
format: (item) => new HtmlString(Html.ActionLink("Edit", "Edit", new { id = item.id ).ToString() + " | " +
Html.ActionLink("Details", "Details", new { id = item.id }).ToString() + " | " +
Html.ActionLink("Delete", "Delete", new { id = item.id }).ToString()))
)
)
#grid.GetHtml(columns: grid.Columns(Html.RoleBasedColumns(grid)))
#{
if (!string.IsNullOrWhiteSpace(grid.SortColumn))
{
<script type="text/javascript">
$('thead > tr > th > a[href*="sort=#grid.SortColumn"]').parent().append('#(grid.SortDirection == SortDirection.Ascending ? "^" : "v")');
</script>
}
}
The RoleBasedColumns(grid) is a helper method in my razor which is
public static WebGridColumn[] RoleBasedColumns(
this HtmlHelper htmlHelper,
WebGrid grid
)
{
var user = htmlHelper.ViewContext.HttpContext.User;
var columns = new List<WebGridColumn>();
var query = from p in _adminModelContainer.Users
select p;
IList<Users> userList = query.ToList();
for (int i = 0; i < userList.Count; i++)
{
// The Prop1 column would be visible to all users
columns.Add(grid.Column("UserName"));
if (userList[i].RolesId == 1)
{
// The Prop2 column would be visible only to users
// in the foo role
columns.Add(grid.Column("Email"));
}
}
return columns.ToArray();
}
I want to show Edit and delete link buttons only for those users whose RolesId is 1.
Using the above functionality the grid is just replicating itself .Columns headers are shown whose rolesid is 1.
I am in a fix.
Any help would be of great use.
Thanks
Do it the easy way and use Telerik's free open source mvc controls (the grid) and when you define your grid.. just use a dynamic column along the lines of:
#(Html.Telerik().Grid(Model)
.Name("Grid").TableHtmlAttributes(new { width="800"})
.Columns(columns =>
{
if (userIsInWhateverRole){
columns.Template(o => Html.Action(GenerateYourLinkStuffHere));
}
columns.Bound(o => o.Address).Width(150);
columns.Bound(o => o.City).Width(120);
columns.Bound(o => o.State).Width(100);
})
.Sortable()
.Scrollable()
.Groupable()
.Filterable()
.Pageable(paging =>
paging.PageSize(5)
.Style(GridPagerStyles.NextPreviousAndNumeric)
.Position(GridPagerPosition.Bottom)))
No other grid is as nice in my opinion - and its free. Why give yourself the headache : )

Resources