Telerik Grid ASP.NET MVC grid binding does not work - asp.net

I have used below code in View and Controller for Grid Binding:
View:
#( Html.Telerik().Grid<MvcApplication1.Models.Movie>()
.Name("Grid")
.EnableCustomBinding(true)
.Columns(columns =>
{
columns.Bound(m => m.Title).Width(100);
columns.Bound(m =>m.Director).Width(200);
columns.Bound(m => m.DateReleased).Format("{0:MM/dd/yyyy}").Width(120);
})
.DataBinding(dataBinding => dataBinding.Ajax().Select("_AjaxBinding", "Home"))
)
Controller:
[GridAction]
public ActionResult _AjaxBinding()
{
return View(new GridModel<Movie> { Data = GetMovies() }); }
private IEnumerable<Movie> GetMovies()
{
return _db.Movie.ToList();
}
But the problem is it is never reaching _AjaxBinding Grid Action.
Please let me know am i missing any web.config changes related to Telerik control.
Thanks in advance

Since you have custom binding enabled, you need to set EnableCustomBinding of the GridActionAttribute attribute of your action method to true.
[GridAction(EnableCustomBinding = true)]
public ActionResult _AjaxBinding(GridCommand command) {
// ...
}
See Custom Ajax Binding.
But judging from the simplicity of your view and controller, it doesn't look like you need custom binding.
See simple Ajax Binding.

Related

ASP.NET CORE Kendo Grid: Populating a grid dynamically

When a user clicks on a date using the Calendar it will populate the grid dynamically with the times. If someone enters data and there is no corresponding record the grid will insert a new record if the user edits an existing row that will fire an update. How do we implement this?
The telerik components operate on a datasource behind the scenes. I find the jquery datasource examples to be helpful for working with them telerik jquery datasource
when you configure your grid and add the save option it will call the sync method on the datasource. the grid will track what types of changes you have made to the datasource ie insert,update,delete and will call the appropriate method for each change that you made.datasource configuration and events. you just need to be sure you have a method in your controller to do what you want with each type of change.
if your grid is setup like below
#(Html.Kendo().Grid<Mymodel>()
.Name("MyGrid")
.Columns(col =>
{
col.Bound(x => x.MyId).Hidden();
col.Bound(x => x.AnotherField).Title("Product Name");
col.Bound(x => x.Athirdfield);
col.Command(cmd => { cmd.Edit(); }).Title("Actions");
})
.ToolBar(tb => { tb.Save(); })
.Editable(ed => ed.Mode(GridEditMode.InLine))
.DataSource(ds => ds
.Ajax()
.Model(md =>
{
md.Id(m => m.MyId);
})
.PageSize(10)
.Read(read => read.Action("Read", "MyGrid"))
.Create(cr => cr.Action("Create","MyGrid"))
.Update(up => up.Action("Update", "MyGrid"))
.Destroy(de => de.Action("Delete", "MyGrid")))
.Filterable()
.Pageable()
)
Now when your grid sees that an insert (or creation) is necessary it will use the method and controller you identified in the .Create() method.
Then your controller just needs to handle the business logic of your operations like below (i only included a read and update method here)
public class MYGridController : Controller
{
private readonly dbContext _context;
public MyGridController(DB context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> Read([DataSourceRequest]DataSourceRequest request)
{
return Json(await _context.MyModel.ToDataSourceResultAsync(request));
}
public async Task<IActionResult> Update([DataSourceRequest]DataSourceRequest request, MyModel pm)
{
try
{
_context.Update(pm);
await _context.SaveChangesAsync();
return Json(await new[] { pm }.ToDataSourceResultAsync(request, ModelState));
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Error");
}
return Json(await new[] { pm }.ToDataSourceResultAsync(request, ModelState));
}
}
I hope this helps. I know how hard it can be to get the hang of these grids, but they are great once you understand how they work

Xamarin Forms: WhenActivated not being fired reactiveui for viewmodel

I can't understand why the WhenActivated func is not fired for a Xamarin Forms application. The application has a LoginViewModel and a LoginView
LoginView: inherits from ContentPageBase which itself derives from : ContentPage, IViewFor which I think is expected
LoginViewModel: ReactiveObject, IRoutableViewModel, ISupportsActivation
Here's the sample application code.
The first view LoginView is loaded as expected. However, I would ideally like to load services and setup bindings in the WhenActivated func but it is not firing. See the LoginViewModel.
Any ideas?
Source code
thanks
Ok ossentoo, I'm not sure why but seems like if you want to use WhenActivated on your viewmodel you must use when activated on your view, the bindings are placed on view's code behind. Here is a little example:
public class LoginViewModel : ViewModelBase /*IRoutableViewModel, ISupportsActivation etc*/
{
this.WhenActivated(disposables =>
{
Debug.WriteLine("ViewModel activated.").DisposeWith(disposables);
});
}
On the view:
public partial class LoginView : ContentPageBase<LoginViewModel>
{
public LoginView()
{
InitializeComponent ();
this.WhenActivated(new Action<CompositeDisposable>(c =>
{
System.Diagnostics.Debug.WriteLine("From View ! (When Activated)");
/*instead of xaml bindings you can use ReactiveUI bindings*/
this.Bind(ViewModel, vm => vm.UserName,
v => v.UserName.Text).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.Password,
v => v.Password.Text).DisposeWith(disposables);
}));
}
}
Let me know if this helped you. :)

Orchard custom module showing blank "Create" page

I created a custom module for Orchard following this wonderful guide.
I have created a controller called BarberAdminController as follows:
[Admin]
public class BarberAdminController : Controller
{
...
public BarberAdminController(IOrchardServices services, IRepository<BarberPart> repository)
{
_repository = repository;
_services = services;
}
...
public ActionResult Create()
{
var barber = _services.ContentManager.New(typeof(BarberPart).ToString());
dynamic model = _services.ContentManager.BuildEditor(barber);
return View(model);
}
}
View:
#{ Layout.Title = T("New Barber").ToString(); }
#using (Html.BeginFormAntiForgeryPost()) {
#Html.ValidationSummary()
// Model is a Shape, calling Display() so that it is rendered using the most specific template for its Shape type
#Display(Model)
}
Upon clicking the link from the admin menu to create a Barber, I get a blank page with nothing but a "Save" button. (URL: /Admin/BarberShop/Barbers/Create)
Does anyone know what I might be doing wrong?
I've set up the routes and admin links and they seem to work fine. I followed the guide as closely as I could on creating the Drivers and Handlers for BarberPart correctly. Including down to the Migration.cs file database schema.
Any help would be great!
I figured it out.
I needed to define a Content Part and Content Type for BarberPart. In Migrations.cs, do:
ContentDefinitionManager.AlterPartDefinition(typeof(BarberPart).Name, p => p
.Attachable(false));
ContentDefinitionManager.AlterTypeDefinition("Barber", t => t
.WithPart(typeof(BarberPart).Name));
In the "Create" method of the Controller, replace:
var barber = _services.ContentManager.New(typeof(BarberPart).ToString());
with:
BarberPart barber = _services.ContentManager.New<BarberPart>("Barber");
Make sure that you have a Drivers/BarberDriver.cs file as such:
public class BarberDriver : ContentPartDriver<BarberPart>
{
protected override DriverResult Editor(BarberPart part, dynamic shapeHelper)
{
return ContentShape("Parts_Barber_Edit", () => shapeHelper.EditorTemplate(TemplateName: "Parts/Barber", Model: part, Prefix: Prefix));
}
protected override DriverResult Editor(BarberPart part, IUpdateModel updater, dynamic shapeHelper)
{
updater.TryUpdateModel(part, Prefix, null, null);
return Editor(part, shapeHelper);
}
}
Be sure to have a part edit template located in /Views/EditorTemplates/Parts/Barber.cshtml that looks like this:
#model SDKU.Barbr.Models.BarberPart
<fieldset>
#Html.EditorFor(model => model.SomePropertyName)
etc...
</fieldset>

Passing JSON data from controller action to a razor view

I would like to know how can I pass data from controller to view in mvc3 razor.
The view is in .cshtml file.
I have a variable in the controller where I am storing the data I need to push to the listbox control in the view.
var results = data.Select(item => new { id = item, label = item.Value, value = item.Key });
Doing this:
return Json(results, JsonRequestBehavior.AllowGet);
Gives me only a popup with the data which needs to be pushed to the listbox:
In the view the listbox resides in accordion control:
<div id="accordion">
#{int i=0;}
#foreach (var item in Model.Parameters)
{
<h3>#Html.LabelFor(m => item.Name, item.Prompt)</h3>
<div>
<div class="editor-field">
<select multiple id="#("Select" +item.Name)" name="#("Select" +item.Name)"></select>
</div>
</div>
i++;
}
</div>
So, I would like to know what should I do to push the items to the listbox instead of showing a popup for the control
Beginner in MVC, Thanks for your understanding.
Thanks in advance, Laziale
EDIT: Json format output
{System.Linq.Enumerable.WhereSelectListIterator<System.Collections.Generic.KeyValuePair<string,string>,<>f__AnonymousType1<System.Collections.Generic.KeyValuePair<string,string>,string,string>>}
returning JSON to your razor view is probably not the best method. I would suggest use a viewModel which is a c# class by itself.
namespace Test
{
public class ViewModel
{
public bool GivingAPresentation { get; set; }
}
}
public class MyController: Controller
{
public virtual ActionResult Index()
{
var model=new ViewModel(){GivingAPresentation =true;}
return View(model);
}
}
Your view code:
#model Test.ViewModel <!-- Note the full namespace -->
<br>GivingAPresentation: #Model.GivingAPresentation </br>
If you are forced to work with a JSON object that is returned from your action then you need to deserialize it first and then work with that object. you can read this post http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx on how to parse JSON to a c# dynamic object.
Let me know if that helps.

asp.net mvc3 disable masterpage for view

How can I disable the usual _Layout.cshtml for one view.
I try to use the content of the view aboutuser.cshtml to populate a div using ajax. Do you think this is a correct approch?
$('#SelectUser').click(function () {
$('#userPlace').html('<strong>Loading...</strong>');
$.post('InfoFor?userSelect=' + ($('#usersoption:selected').val()), function (data) {
$('#userPlace').html(data);
});
});
Inside this view/partial:
#{
Layout = null;
}
or from the controller action serving it return a PartialView instead of a View:
public ActionResult Foo()
{
return PartialView();
}

Resources