How do i call the controller in mvc kendoui grid
here is the code:
but not working:
.ClientTemplate(string.Format("<a class=\"modal\" rel=\"/address/#= Id #/map\" close=\"{0}\" title=\"{1}\"><img src=\"/content/images/ico_edit_16.png\" /></a>",
T("Common.Close").Text,
T("Address.MapAddress").Text)
here is the controller:
public ActionResult AddressMap( int accountId)
{
//load default accounts
var listModel = new AddressListModel();
//{
// AccountId = accountId,
// GridPageSize = _commonSettings.GridPageSize,
//};
//listModel.Addresses = new List<AddressModel>();
return View(listModel);
}
Using your existing code:
.ClientTemplate(string.Format("<a class=\"modal\" rel=\"/address/#= Id #/map\"
close=\"{0}\" title=\"{1}\"><img src=\"/content/images/ico_edit_16.png\" /></a>",
T("Common.Close").Text,
T("Address.MapAddress").Text)
You will see you are setting the a tag's rel setting rather than the href property.
so all you should need to do is change the tag so it is more like this:
(string.Format("<a class='k-link' href='{2}' close='{0}' title='{1}'><img src='/content/images/ico_edit_16.png' />#=Id#</a>",
T("Common.Close").Text,
T("Address.MapAddress").Text, #Url.Action("AddressMap", "{Your Controller}", new {accountId= "#=Id#"})))
All I have done is passed the url into the string formatter and then bound the accountId to the Id that is passed into the row from the dataItem.
I have also added the Id to the link so you can see what is being presented.
If this isn't what you wanted then let me know what you actually need and I will amend the answer accordingly
Related
I'm developing a custom field type that extends from LookupEx. The purpose of the control is to allow the user to select from the drop down, and based upon that selection populated additional fields of type Multilist.
public class CascadingDroplink : LookupEx
{
private const string sourceFieldName = "CascadingDroplink";
protected override void DoRender(System.Web.UI.HtmlTextWriter output)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<script type=\"text / javascript\">");
sb.AppendLine(" var $j = jQuery.noConflict(); ");
sb.AppendLine(string.Format(" $j(\"#{0}\").change(function(event) {{ ", this.ID));
sb.AppendLine(string.Format("scForm.invoke('contenteditor:save', event);"));
sb.AppendLine(string.Format(" }});"));
sb.AppendLine("</script>");
output.Write(sb.ToString());
Fromt the embeded javascript, you can see I have found a way to perform a callback by simulating the click even of the Save button:
scForm.invoke('contenteditor:save', event);
And while this works, the content editor is refreshed, and the Multilist fields are updated with custom datasources, saving isn't ideal because there could be validation present.
How can the contenteditor be refreshed, as if the area was within a callback panel, without calling save?
Thanks!
I have a MVC 3 applicaiton in which I pass a vewmodel from the controller to the view. The vewmodel contains a couple of List<> properties.
public ActionResult MainView()
{
var model = GetViewModel();
return View("SignificantEventsView", model);
}
private SignificantEventsViewModel GetViewModel()
{
var viewModel = new SignificantEventsViewModel();
List<County_Codes> countyCodes = GetCountyCodeList();
List<String> stateNames = countyCodes.OrderBy(o=>o.County_st).Select(o => o.County_st ).Distinct().ToList();
viewModel.selectedState = stateNames.FirstOrDefault();
viewModel.CountyCodesList = countyCodes;
viewModel.StateNames = stateNames;
viewModel.SelectedCounties = new String[]{};
viewModel.SelectedCountyCodes = new String[] { };
viewModel.UnSelectedCounties = new String[] { };
viewModel.UnSelectedCountyCodes = new String[]{};
return viewModel;
}
The View looks like this:
#model ServicingPortal.ViewModels.SignificantEventsViewModel
#{
ViewBag.Title = "Significant Events";
}
<h2>SignificantEvents</h2>
#using (Html.BeginForm("RefreshCounties", "SignificantEvents", FormMethod.Post, new { id = "significantEventsForm", Model }))
{
<fieldset>
<span class="SpanTextboxEdit">
#Html.Label("states", "States")
<br />
<br />
#Html.DropDownListFor(o => #Model.selectedState
, new SelectList(Model.StateNames)
, new { id = "stateDropDown", onchange = "submit()", name = "test" })
</span>
</fieldset>
...
}
When the StateDropdownList is changed the veiwmodel is passed back to the controller, but the countyCodes list is always null.
I tried adding #Html.HiddenFor(o => #Model.CountyCodesList) in the view, but it still returns null. The only values that don't seem to be null are the primitive types such as String or String[]. Even the List stateNames is null.
I don't want to rebuild the county code list on each post back because there is substantial overhead involved. I have to create the list from all active loans in the database, of which there are thousands.
How can I get a List<> to persist from the view to the controller?
I should explain what I'm trying to acheive here.
I have a dropdown and a multiselect list box. The dropdown contains states and the listbox contains counties filtered by the selected state.
I need to filter the listbox contents when the selected state changes.
It would make sense to perform this task on the client side, but I have not found a good solution.
I will admit my javascript skills are quite limited.
All the solutions I researched one way or another involved filtering the county list on the server side.
I can accomplish this on the server side easy enough, but I thought that since I have already built the list, why not keep it intact instead of going to the backend each time.
The short answer is that you can't really do what you're trying to do. You're kind of trying to solve the wrong problem. You should look at using caching on the server side to prevent going back to the database to construct the county list every time.
I solved this by using TempData. On the postback action I can get the County List from temp data and set the ViewModel CountyCodeList to this value.
This must be simple and I'm being incredibly dense but I can't find an example to help me figure it out. I want to filter my list of tblAsset items by their assessmentId which is passed in through a parameter. I'm able to get the parameter value ok, but I'm not sure how to write the query.
My model is built from an existing Database using the Model creation wizard.
Thanks for any help!
public IEnumerable<tblAsset> GettblAssets()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
var assessmentId = nvc["aid"];
//limit the assets by assessmentId somehow and return
}
You could use the .Where extension method on the IQueryable<tblAsset> instance returned by your database:
public IEnumerable<tblAsset> GettblAssets()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
var assessmentId = nvc["aid"];
// TODO: you might need to adjust the property names of your model accordingly
// Also if the assessmentId property is an integer on your model type
// you will need to parse the value you read from the request to an integer
// using the int.Parse method
return db.tblAsset.Where(a => a.assessmentId == assessmentId);
}
I am using JQGrid with the Trirand.Web.Mvc class, and trying to figure out how to do custom paging.
I have seen the paging demos here
The problem with these demos is that they bind directly to a linq context object and lets MVC take care of the paging.
// This method is called when the grid requests data. You can choose any method to call
// by setting the JQGrid.DataUrl property
public JsonResult PerformanceLinq_DataRequested()
{
// Get both the grid Model and the data Model
// The data model in our case is an autogenerated linq2sql database based on Northwind.
var gridModel = new OrdersJqGridModel();
var northWindModel = new NorthwindDataContext();
// return the result of the DataBind method, passing the datasource as a parameter
// jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc
return gridModel.OrdersGrid.DataBind(northWindModel.OrdersLarges);
}
The data set I want to bind to is quite complex and I am returning it from a stored procedure, which does the paging for me.
So all I have to give JQGrid is the correct size of rows for a specific page of the entire resultset. I can also return the total row count.
So I have my results in a List myListOfObjects.
I can pass this into the DataBind using myListOfObjects.AsQueryable()
The problem is, JQGrid thinks there is only {page size} rows, so does not display any of the paging options.
Is it possible to pass in the total row count?
Other grids, like Teleriks MVC grid allows you to pass in the Total row count, and it displays the paging correctly
Ok, so I've managed to solve this myself. There may be other ways to do it, if so I'd love to hear them!
The JQGrid.DataBind produces an JsonResult object, whose Data value is set to Trirands own object Trirand.Web.Mvc.JsonResponse
It's an internal class to their Trirand.Web.Mvc, so i had to copy its structure which I could see using Visual Studio debugging.
It has:
page - the current page number
records - the total record count
rows - of type Trirand.Web.Mvc.JsonRow (which I need to replicate too)
total - the total number of pages needed
JsonRow looks like:
cell - a string array of your columns
id - your row ID
So my code looked like this:
var jsonList = new List<JSONRow>();
myData.ForEach(x => jsonList.Add(new JSONRow(x)));
var jsonResult = Json (new
{
page = page,
rows = jsonList.ToArray(),
records = totalRows,
total = Math.Round((double)totalRows / rows, MidpointRounding.AwayFromZero)
}, JsonRequestBehavior.AllowGet);
return jsonResult;
My JsonRow looks like this:
public class JSONRow
{
public string[] cell { get; set; }
public string id { get; set; }
public JSONRow(MyObjectType myObject)
{
id = myObject.id;
cell = new string[3];
cell[0] = myObject.Col1;
cell[1] = myObject.Col2?? "";
cell[2] = myObject.Col3?? "";
}
}
I am planning on creating a custom route using ASP.NET Web Pages by dynamically creating WebPage instances as follows:
IHttpHandler handler = System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath("~/Default.cshtml");
How can I supply an object to the underlying WebPage object so that it can become the web pages's "Model"? In other words I want to be able to write #Model.Firstname in the file Default.cshtml.
Any help will be greatly appreciated.
UPDATE
By modifying the answer by #Pranav, I was able to retrieve the underlying WebPage object using reflection:
public void ProcessRequest(HttpContext context)
{
//var page = (WebPage) System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath(this.virtualPath);
var handler = System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath(this.virtualPath);
var field = handler.GetType().GetField("_webPage", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var page = field.GetValue(handler) as System.Web.WebPages.WebPage;
var contextWrapper = new HttpContextWrapper(context);
var pageContext = new WebPageContext(contextWrapper, page, context.Items[CURRENT_NODE]);
page.ExecutePageHierarchy(pageContext, contextWrapper.Response.Output);
}
Unfortunately this is not reliable as it does not work in Medium Trust (BindingFlags.NonPublic is ignored if application is not running in full trust). So while we have made significant progress, the solution is not yet complete.
Any suggestions will be greatly appreciated.
The Model property of a WebPage comes from the WebPageContext. To set a Model, you could create a WebPageContext with the right parameters:-
var page = (WebPage)WebPageHttpHandler.CreateFromVirtualPath("~/Default.cshtml");
var httpContext = new HttpContextWrapper(HttContext.Current);
var model = new { FirstName = "Foo", LastName = "Bar" };
var pageContext = new WebPageContext(httpContext, page, model);
page.ExecutePageHierarchy(pageContext, httpContext.Response.Output);
The model instance should now be available as a dynamic type to you in your page.