Custom Client Template Telerik Grid - asp.net-mvc-3

I'm kind of new using Telerik Grid, basically what I'm trying to accomplish here is the following scenario, I have a form that have some fields and via ajax calls another action on my controller to generate the model to a partial view that have the following grid, my problem is that I need to create some actions depending on some business logic, I know I can do that using a column template, the thing is that since im using ajax binding it "loose" my template, looking around on internet I found that you can do that using a js function go generate the links, my question is isn't that kind of messy? im duplicating the same business logic on the server and on the client, there's must be a better way to accomplish this?
Html.Telerik().Grid(Model)
.Name("Grid")
.DataBinding(binding => binding.Ajax().OperationMode(GridOperationMode.Client))
.Columns(column =>
{
column.Bound(c => c.Id).Title("Id").Width(30);
column.Bound(c => c.Status);
column.Bound(c => c.DateReg);
column.Template(
#<text>
<div class="ActionsProvGrid">
<a href="#Url.Action("SomeAction", "Controller", new {id = item.id})">
<img src="../../Content/icons/ViewMore.png" alt="ViewMore" />
</a>
#if (#item.Status.Equals("ACT"))
{
<a href="#Url.Action("SomeOtherAction", "Controller", new {idOportunidad = item.id})">
<img src="../../Content/icons/invoice.png" alt="invoice"/>
</a>
}
</div>
</text>
).ClientTemplate("<#= GenearteIcons(data) #>");
})
.Sortable()

As a solution you can define property on your model that encapsulates the result of your business logic:
public bool DoesStatusEqualToAct {
get
{
return (code that determines if it's true);
}
}
And in JavaScript function that generates a link html you can access this property:
function GenerateIcons(data){
var html = '';
if(data.DoesStatusEqualToAct){
html = 'version 1';
}
else{
html = 'version 2';
}
return html;
}

Related

partial views to get data and then post the results to save in database

I am very new to MVC, let me try to explain my scenario in plain simple English:
I have an strongly typed mvc form/page (Product.cshtml) with a model, say ProductViewModel.
This page has got two search buttons, one to search and bring the items to be added to the Product and other to bring in the location, most probably partial views.
Now, what I want is that these search results work in ajax form without complete post back, and then the results of these searches (items and location) should be posted back using model binding to the form when user clicks on the submit button.
What could be the best way of achieving this functionality?
Immediate responses will be well appreciated.
I thought, its good to share the complete code for clarity:
I have one form(Service1.chtml) that has a partial view to display users(_TestUser a partial view:read only), then another partial view(_PlotServiceRequestData) that should have a field to search the plot and bring back the details lke its owner name and landuser etc.
Then when I click on submit button of the main form, I should be able to read all data(main form) + new data from _PlotServiceRequestData partial view and save all data to database.
I was trying one more option, that is, to use #Ajax.ActionLink on Service1.cshtml to call the _GetPlotDetails method and then store partial view data in TempData, so that it is available to the form when users clicks on "Submit" button of Service1.cshtml, is this a right approach?, if I use ajax.BeginForm inside partial view then the data is posted to the
Service1 controller method which is actually to save the form data and not to update the partialview and in this method even I am not getting model data of the partial view.
Sevice1.cshtml:
#model ViewModels.TestViewModel
#{
ViewBag.Title =
"Service1";
}
#
using (Html.BeginForm())
{
#Html.LabelFor(m => m.Title)
#Html.EditorFor(m => m.Title)
#Html.Partial(
"_TestUser", Model)
<div id="RequestPlotData">
#Html.Partial(
"_PlotServiceRequestData", Model.requestData)
</div>
<button type="submit">Save Form</button>
}
#section Scripts {
}
_PlotServiceRequestData.cshtml:
===============================
#model ViewModels.PlotServicesRequestDataViewModel
<
div id="RequestPlotData">
#
using (Ajax.BeginForm("_GetPlotDetails", "Test", new AjaxOptions { UpdateTargetId = "RequestPlotData", Url = Url.Action("_GetPlotDetails","Test") }))
{
<h1>Request Details</h1>
 
<div>
#Html.LabelFor(m => m.plotAddress)
#Html.EditorFor(m => m.plotAddress)
<input type="submit" name="submit" value="Ajax Post" />
</div>
<div>
#Html.LabelFor(m => m.LandUser)
#Html.EditorFor(m => m.LandUser)
</div>
<div>
#Html.LabelFor(m => m.OwnerName)
#Html.EditorFor(m => m.OwnerName)
</div>
}
</
div>
CONTROLLER:
==========
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
namespace
TestNameSpace
{
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Service1()
{
Injazat.AM.mServices.
LocalDBEntities context = new Injazat.AM.mServices.LocalDBEntities();
TestViewModel model =
new TestViewModel() { user = context.Users.First(), Title = "Land Setting Out",
requestData =
new PlotServicesRequestDataViewModel() { ServiceNumber ="122345", TransactionDate="10/10/2033" } };
return View(model);
}
[
HttpPost()]
public ActionResult Service1(TestViewModel model)
{
PlotServicesRequestDataViewModel s = (PlotServicesRequestDataViewModel)TempData[
"Data"];
TestViewModel vm =
new TestViewModel() { user = model.user, requestData = s, Title = model.Title };
return View(vm);
 
}
[
HttpGet()]
//public PartialViewResult _GetPlotDetails(string add)
public PartialViewResult _GetPlotDetails(PlotServicesRequestDataViewModel requestData)
{
//PlotServicesRequestDataViewModel requestData = new PlotServicesRequestDataViewModel() { plotAddress = add};
requestData.OwnerName =
"owner";
requestData.LandUser =
"landuser";
TempData[
"Data"] = requestData;
return PartialView("_PlotServiceRequestData", requestData);
}
}
}
You can probably use the jQuery Form plugin for this. This makes the process of posting the data from your form back to the server very easy. The form would post to an action that would return a partial view that you can then push into your UI.
To make this easier, jQuery form actually has a "target" option where it will automatically update with the server response (ie. the partial view returned from your search action).
View
<form id="searchForm" action="#(Url.Action("Search"))" method="POST">
<input name="query" type="text" /> <!-- order use Html.TextBoxFor() here -->
<input type="submit" />
</form>
<div id="result"><!--result here--></div>
Javascript
$('#searchForm').ajaxForm({
target: '#result'
});
Controller
public ActionResult Search(string query)
{
// Do something with query
var model = GetSearchResults(query);
return Partial("SearchResults", model)
}
This should hopefully help you to get on the right track. jQuery Form is a good plugin and is the main thing you should look into for ajaxifying your form posts back to the server. You might also want to look into using jQuery's $.post and $.ajax functions, but these require slightly more work.

Multiple views for one model in AngularJS

I'm learning AngularJS framework and my background is BackboneJS and it seems I can not figure
out conventional way to do next thing:
I have a readonly list of elements each of which has 'edit' button that switches this
particular element to an edit mode. In edit mode I need to render input elements instead
of spans, p's etc.
The way to do this in Backbone.js is simply create EditView and pass model to it, but I don't have any idea how this works in Angular.
I pass data to the scope and render the readonly list and when user clicks on 'edit' button
in the element how should I change view for the element?
Thanks!
Angular makes this task simpler than Backbone by using a model for editing, then you update the original list and clear the edit model.
The view:
<div ng-app='App'>
<div ng-controller='mainCtrl'>
<div ng-controller='childCtrl'>
<strong>Controller</strong>
<ul>
<li ng-repeat='item in list'>{{item.name}} <button ng-click='edit($index)'>+</button></li>
</ul>
<div ng-show='editModel.name'>
Name: <input type="text" ng-model='editModel.name'/> <button ng-click='save()'>Save</button><button ng-click='cancelEdit()'>Cancel</button>
</div>
</div>
</div>
The angular app:
angular.module('App', [])
.controller('mainCtrl', ['$scope', function($scope){
$scope.list = [ {name:'item 1'}, {name:'item 2'}, {name:'item 3'} ];
}])
.controller('childCtrl', ['$scope', function($scope){
$scope.editModel = {};
$scope.edit = function(index){
$scope.editModel.index = index;
$scope.editModel.name = $scope.list[index].name;
};
$scope.cancelEdit = function(){
$scope.editModel = {};
};
$scope.save = function(){
if($scope.editModel.hasOwnProperty('index')){
$scope.list[$scope.editModel.index] = $scope.editModel;
}
else if($scope.editModel.name && $scope.editModel.name.length){
$scope.list.push($scope.editModel);
}
$scope.cancelEdit();
};
}]);
JsFiddle: http://jsfiddle.net/guilhermenagatomo/Bp6bY/
I'm using the controller nesting so the list can be used by other controllers you have in the app, or maybe you can create a controller just to take care of the editing.

Telerik ASP.NET MVC 3 Grid - setting row background

I'm using Telerik Grid. I need to set background color for the entire row based on some property in view model. I've tried to do it as below by setting a background in IF statement for each column but backgound applies only on element not all cell (td). Also it seems it's a very "dirty" way to accomplish this task.
#(Html.Telerik().Grid(Model.SomeItems).Name("Grid")
.Columns(columns =>
{
columns.Template(
#<text>
#if (Model.IsOfSpecialColor)
{
<div class="gridRowBackground">
#Html.ActionLink(...)
</div>
}
else
{
#Html.ActionLink(...)
}
</text>).Title("Blabla");
});
You can change it using onRowDataBound event
#(Html.Telerik().Grid<Customer>()
.Name("Grid2")
.DataBinding(d => d.Ajax().Select("Select", "Home"))
.ClientEvents(e => e.OnRowDataBound("onRowDataBound"))
)
and the function is
<script>
function onRowDataBound(e) {
if (e.dataItem.ID == 2) {
e.row.style.backgroundColor = "grey";
}
}
</script>
If you are using server data binding, you can use CellAction. However, if you are using ajax data binding, you will need to use a solution like Tassadaque suggests.
#(Html.Telerik().Grid(Model.SomeItems)
.Name("Grid")
.CellAction(cell =>
{
if (cell.DataItem.IsOfSpecialColor.Value)
{
cell.HtmlAttributes["style"] = "background-color: red";
}
})

MVC3 Nesting Partial Views with a call to Ajax.ActionLink

I am aware of the previous two questions which talk about nesting partial views but the solutions don't work for my design (which might not be the best one but I'm unsure how to adapt it).
Background:
I collect questionnaire responses from users and store them on an sql server as xml files.
I have a partial view which loads a table with all the Responses of a given user, this partialview populates the table with things like Response date, link to xml response document, questionnaire name, link to xml questionnaire document (the questionnaire info is pulled from a different table) and an Ajax ActionLink which redirects to action which parses the two relevant xml documents to print out Question and Answer list (i.e. visualise the response to be human readable) inside the second partial view.
The first partial view contains a div underneath the table which I wish to populate onclick of the Ajax.ActionLink with the second partial view.
Problem:
The answers are rendered correctly however the partial view is loaded into a whole new page, without any styling.
The other solutions to this nesting problem use RenderPartial() however I use return PartialView()
Code:
First Partial View:
<table>
<thead>
<tr><th>headers with other info</th>
<th>Display(/th>
<tr>
</thead>
<tbody>
<tr><td>cells with other info</td>
<td>#Ajax.ActionLink("View", "DisplayResponse","HealthStatus", new { respID = item.UniqueID,qVersion=item.QuestionnaireVersion, qname = item.QuestionnaireName }, new AjaxOptions { UpdateTargetId = "responseDisp" })</td>
</tbody>
</table>
<div id="responseDisp"></div> <--- **This is the div I wish to populate, does anyone know why it's not working?**
DisplayResponse Action (without the logic for parsing the xml documents)
public ActionResult DisplayResponse(Guid respID, int qVersion, String qname) {
var allResponses = ZData.Responses;
var response = (from r in allResponses
where r.UniqueID == respID
select r
).First();
//geting an XML questionnaire document
var questionnaireDetails = ZodiacData.Questionnaires;
var questionnaire = (from q in questionnaireDetails
where q.Name == qname && q.Version == qVersion
select q
).First();
//creating XMLDocument to read the questionnaire
XmlDocument xqdoc = new XmlDocument();
xqdoc.LoadXml(questionnaire.Xml);
XmlElement qroot = xqdoc.DocumentElement;
ViewBag.qroot = qroot;
XmlDocument xrdoc = new XmlDocument();
xrdoc.LoadXml(response.Raw);
XmlElement rroot = xrdoc.DocumentElement;
ViewBag.rroot = rroot;
return PartialView("_PrintedResponse");
}
I would be grateful for any help!
In MVC3 the #AJax. helpers are rendering regular form and a tags with some extra data- attributes. To make the magic work some Javascript is needed which will use this generated data- attributes to make the necessary jQuery ajax calls.
These js functions are living in the jquery.unobtrusive-ajax.js so add this line to your layout or view and it should work:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"
type="text/javascript"></script>
First, as mentioned above, you must have a reference to the jquery.unobtrusive-ajax.js file as this will get things "wired" up correctly for you.
This answer is also in response to your comment on your question about how you're passing your models to your views. You are actually making things more complicated for yourself by using the ViewBag for your model.
By using the ViewBag for your models, you will have a harder time finding/fixing/resolving issues in typo's as well as the great features of the Razor helpers. The ViewBag is a dynamic object and there are no compile time type checks. You don't need to cast your objects either (less code).
The preferred (and best practice) is to hook things up like so:
1) Your controller contains ViewModels (Strongly Typed) that are passed to the ViewModels
Controller
public ActionResult Something() {
return View();
}
public ActionResult UserView() {
UserViewModel mdoel = new UserViewModel {
Email = "me#somewherecool.com",
FirstName = "Your",
SStatuses = new List<SStatus>{
new SStatus {
ID = 0
}
}
};
return PartialView("_SomethingPartial", mdoel);
}
Index ("Something" view)
#{
ViewBag.Title = "Something";
}
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<h2>Something</h2>
#Ajax.ActionLink("Ajax Click", "UserView", new AjaxOptions { UpdateTargetId = "MyDivContainer", InsertionMode = InsertionMode.Replace })
<div id="MyDivContainer">
<!-- my content should be here -->
</div>
Partial View
#model StackModels.UserViewModel
<div class="par">
#Html.LabelFor(m => m.FirstName)
<div class="field">
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
</div>

MVC 3 EditorTemplate - Model properties are empty

I have a number of custom EditorTemplates for various model classes. Inside these templates I obviously need to reference the properties of the model. My problem is that when I use the direct syntax of Model.Id (for example), the value is null. Another example is Model.Name which returns an empty string. However, when I reference the model in an expression (eg. #Html.TextBoxFor(i => i.Name)) then the values are there.
To further illustrate, here is a code snippet:
#model Vigilaris.Booking.Services.CompanyDTO
<div>
<fieldset class="editfieldset">
<legend class="titlelegend">Company Details</legend>
<ol>
<li>
#Html.TextBox("tb1", #Model.Id)
#Html.TextBox("tb2", #Model.Name)
</li>
<li>
#Html.LabelFor(i => i.CreatedDate)
#Html.DisplayFor(i => i.CreatedDate)
</li>
<li>
#Html.LabelFor(i => i.Name)
#Html.TextBoxFor(i => i.Name)
</li>
<li>
#Html.LabelFor(i => i.Description)
#Html.TextAreaFor(i => i.Description)
</li>
<li>
#Html.LabelFor(i => i.Phone)
#Html.TextBoxFor(i => i.Phone)
</li>
</ol>
</fieldset>
</div>
In this example, all the code that is using the LabelFor and DisplayFor helper functions displays the data from the model. However, the Html.TextBox code portion returns 0 for Model.Id and empty string for Name.
Why does it not access the actual model data when I reference Model directly?
I am unable to reproduce this. You might need to provide more context (controllers, views, ...). Also shouldn't your textbox be named like this:
#Html.TextBox("Id", Model.Id)
#Html.TextBox("Name", Model.Name)
and also why not using the strongly typed version directly:
#Html.TextBoxFor(x => x.Id)
#Html.TextBox(x => x.Name)
I managed to figure this one out. One thing I left out in my problem description was that I am using Telerik MVC Grid extension and the EditorTemplate is being using for In-form editing. So, the Model properties are not available at this point and this is understandable behaviour. I had to use a client side onEdit event on the Telerik MVC Grid and then set these values as necessary.
How I remember solving this is that I added a ClientEvent in my Telerik MVC Grid as follows:
.ClientEvents(events => events.OnEdit("Users_onEdit"))
This tells the grid to run my javascript function called Users_onEdit when an edit is triggered. Then, in my javascript function I find the field I want and then set its value. Here is an code excerpt:
function Users_onEdit(e) {
if (e.mode == "insert") {
$("#UserName").removeAttr("readonly");
$("#UserName").removeAttr("title");
$("#divNewUserMessage").show();
var formId = String(e.form.id);
var formIndex = formId.indexOf("form");
var companyId = formId.substr(6, formIndex -6);
var hiddenCompanyId = $(e.form).find("#CompanyId");
hiddenCompanyId.val(companyId);
}
}
I hope this helps others out there.

Resources