Telerik Forums
UI for ASP.NET MVC Forum
2 answers
264 views
Hi,

I have an mvc4 project with entity framework 4.1 and a data model with a timespan, which I need to bind to a grid and update, via Ajax, using a time picker in an editor template, in grid popup edit mode.

I can format the timespan to display correctly on read, but on edit I just cannot work out the right pattern.  I understand the issue is due to how Json deals with timespans.   This seems to be an issue which is causing a few some big headaches, so I would like to ask for a recommended pattern for binding to a timespan and a code example please.

Thanks
Rich
Richard
Top achievements
Rank 1
 answered on 01 May 2013
3 answers
127 views
Hi,
I have a list of checkboxes, but when I click to check one all checkboxes is checked.
This is when using Ajax binding:
<input id="SelectedRoles_Administrators" type="checkbox" value="Administrators" name="SelectedRoles" data-bind="checked:SelectedRoles">
<label for="SelectedRoles_Administrators">Administratör</label>
   
<input id="SelectedRoles_SuperAdministrators" type="checkbox" value="SuperAdministrators" name="SelectedRoles" data-bind="checked:SelectedRoles">
<label for="SelectedRoles_SuperAdministrators">Superadministratör</label>
But when using Server binding it works as it should:
<input id="SelectedRoles_Administrators" type="checkbox" value="Administrators" name="SelectedRoles">
<label for="SelectedRoles_Administrators">Administratör</label>
    
<input id="SelectedRoles_SuperAdministrators" type="checkbox" value="SuperAdministrators" name="SelectedRoles">
<label for="SelectedRoles_SuperAdministrators">Superadministratör</label>
Is it some sort of a bug or is the code wrong typed in some way?
Original code:
@foreach (var role in roles)
 {
    <input type="checkbox" name="SelectedRoles" id="SelectedRoles_@(role.Enum)" value="@role.Enum"  /><label for="SelectedRoles_@(role.Enum)">@role.Text</label>
}
/Mattias
Daniel
Telerik team
 answered on 01 May 2013
2 answers
2.9K+ views
I am trying to bind an enum to a dropdown list. I am successful using the vanilla @Html.DropDownListFor, but unsuccessful with the @Html.Kendu().DropDownListFor.

My enum provider is:
public static IEnumerable<SelectListItem> SexListItems
{
    get
    {
        foreach (var value in Enum.GetValues(typeof(Sex)))
        {
            string name = string.Format("Sex.{0}", Enum.GetName(typeof (Sex), value));
            var text = Resources.Shared.EnumStrings.ResourceManager.GetString(name);
            yield return new SelectListItem() {Value = value.ToString(), Text = text};
        }
    }
}


The following code works well, showing the list and binding to the  property::
@Html.DropDownListFor(p => p.Sex, DataProviders.SexListItems)


However, the following displays the list, but does not bind to the property:
               
@Html.Kendo().DropDownListFor(p => p.Sex).BindTo(ELSORegistry.DataProviders.SexListItems)

 

 

 


Steve
Top achievements
Rank 1
 answered on 30 Apr 2013
4 answers
511 views
I am trying to override the current theme and create a Kendo window having a semi transparent PNG as a background (window will be see through somewhat).

In the window creation I have the following - but it's not working - it's still defaulting to the current theme's window background color:

.HtmlAttributes( new { style="background-color:transparent;background-image:'/images/bg_trans_60.png';background-repeat:repeat;"} )

Please advise.

Thanks.
Rene
Top achievements
Rank 1
 answered on 30 Apr 2013
1 answer
115 views
Hi. New to MVC and trying to implement my first kendo control using the example provide by Kendo, I can get data loaded in the razor view and kendo grid, but if I try to update, edit, or delete it does not execute the code, I get no exception thrown.. 

What am i missing that these functions dont execute?

Here is the code for view and controller:

.DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Events(events => events.Error("error_handler"))
        .Model(model => model.Id(p => p.ID))
        .Create(update => update.Action("EditingPopup_Create", "SysAdminController"))
        .Read(read => read.Action("EditingPopup_Read", "SysAdminController"))
        .Update(update => update.Action("EditingPopup_Update", "SysAdminController"))
        .Destroy(update => update.Action("EditingPopup_Destroy", "SysAdminController"))

public ActionResult EditingPopup_Read([DataSourceRequest] DataSourceRequest request)
{
    throw new NotImplementedException();
}
 
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditingPopup_Create([DataSourceRequest] DataSourceRequest request, MenuTabViewViewModel menuTabViewViewModel)
{
    throw new NotImplementedException();
}
 
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditingPopup_Update([DataSourceRequest] DataSourceRequest request, MenuTabViewViewModel product)
{
    throw new NotImplementedException();
}
 
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditingPopup_Destroy([DataSourceRequest] DataSourceRequest request, MenuTabViewViewModel product)
{
    throw new NotImplementedException();
}
Robert
Top achievements
Rank 1
 answered on 30 Apr 2013
1 answer
194 views
I have SQL Express running as default database
I open the demos and click on the following link.
http://localhost:54833/razor/web/menu/modelbinding

I get this error (no details about server and/or database connection are provided):

Server Error in '/' Application.A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Source Error:

Line 1: @model IEnumerable<Kendo.Mvc.Examples.Models.Category>
Line 2:
Line 3: @(Html.Kendo().Menu()
Line 4: .Name("Menu")
Line 5: .BindTo(Model, mappings =>
Source File: c:\Program Files (x86)\Telerik\Kendo UI for ASP.NET MVC Q1 2013\wrappers\aspnetmvc\Examples\Areas\razor\Views\web\menu\modelbinding.cshtml    Line: 3

Stack Trace:

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296071
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5308555
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +920
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5311099
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +37
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +558
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +67
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1052
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +78
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +167
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +143
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +83
System.Data.SqlClient.SqlConnection.Open() +96
System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user) +43
System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe() +41
System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode() +21
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +57
System.Data.Linq.Table`1.GetEnumerator() +41
System.Data.Linq.Table`1.System.Collections.IEnumerable.GetEnumerator() +4
Kendo.Mvc.UI.NavigationItemContainerExtensions.BindTo(INavigationItemContainer`1 component, IEnumerable dataSource, Action`1 factoryAction) +100
Kendo.Mvc.UI.Fluent.MenuBuilder.BindTo(IEnumerable dataSource, Action`1 factoryAction) +20
ASP._Page_Areas_razor_Views_web_menu_modelbinding_cshtml.Execute() in c:\Program Files (x86)\Telerik\Kendo UI for ASP.NET MVC Q1 2013\wrappers\aspnetmvc\Examples\Areas\razor\Views\web\menu\modelbinding.cshtml:3
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +222
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +295
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +324
System.Web.Mvc.Controller.ExecuteCore() +106
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +91
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +48
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629296
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18034                 
Vladimir Iliev
Telerik team
 answered on 30 Apr 2013
2 answers
70 views
I have an MVC4 application with a MVC defined Grid with CRUD operation. I am using inline Create and get a strange phenomena when I enter two entries in a row. The scenario is as follows:
  1.  I click 'Add New Item' button and an empty row appears at the top of the grid with the two editable items open for input.
  2. I enter the date new entry and click the 'Update' button.
  3. I see a single POST go back to the MVC application and the create works correctly.
  4. As the next immediate step I then press 'Add New Item' button again and enter  a new entry.
  5. On pressing the 'Update' button I see TWO Posts go back to the MVC application.
           - The first is the new entry
           - The second is the data for the entry entered in steps 1 to 3.

That is rather strange, and my database, which does not allow entries with the same name fails the second (duplicate) entry. If I press F5 or next page on the grid after step 3 then I do not have this problem.

My .razor view is:

@{
    ViewBag.Title = "Services";
}
 
<h2>Services</h2>
 
@*<div id="message" class="Message"></div>*@
@Html.AntiForgeryToken()
 
@(Html.Kendo().Grid<ServiceLayer.Models.DTOs.SmServiceDto>()
      .Name("Services")
      .Columns(columns =>
                   {
                       columns.Bound(p => p.SmServiceId).Hidden();
                       columns.Bound(p => p.ShortName);
                       columns.Bound(p => p.FullName);
                       columns.Bound(p => p.Locked);
                       columns.Command(command => { command.Edit(); command.Destroy(); }).Width(172);
                   })
      .ToolBar(toolbar => toolbar.Create())
      .Editable(editable => editable.Mode(GridEditMode.InLine))
      .Pageable()
      .Sortable()
      //.Scrollable()
      //.HtmlAttributes(new {style = "height:430px;"})
      .DataSource(dataSource => dataSource
                                    .Ajax()                               
                                    .PageSize(10)
                                    .Events(events => events.Error("error_handler"))
                                    .Model(model =>
                                               {
                                                   model.Id(p => p.SmServiceId);
                                                   model.Field(x => x.SmServiceId).Editable(false);
                                                   model.Field(x => x.Locked).Editable(false);
                                               })
                                    .Create(x => x.Action("AjaxServiceCreate", "Model").Data("sendAntiForgery").Type( HttpVerbs.Post))
                                    .Read(read => read.Action("AjaxServiceRead", "Model"))
                                    .Update(x => x.Action("AjaxServiceUpdate", "Model").Type( HttpVerbs.Post).Data("sendAntiForgery"))
                                    .Destroy(x => x.Action("AjaxServiceDelete", "Model").Type( HttpVerbs.Post).Data("sendAntiForgery"))
      ))
       
@section scripts {
<script type="text/javascript">
    function error_handler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
        }
    
 
    function sendAntiForgery() {
        return { "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() };
    }
 
</script>
}

The MVC actions are pretty standard copies of the format on your examples site, but with ValidateAntiForgeryToken added.

[AllowAnonymous]
        public ActionResult Services(IListSmService service)
        {
            return View();
        }
 
        [AllowAnonymous]
        public ActionResult AjaxServiceRead([DataSourceRequest]DataSourceRequest request, IListSmService service)
        {
            return Json(service.GetList().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }
 
        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateAntiForgeryToken]
        public ActionResult AjaxServiceCreate([DataSourceRequest] DataSourceRequest request, ISmServiceDto newItem, ICreateSmService service)
        {
            if (newItem != null && ModelState.IsValid)
            {
                var response = service.Create(newItem);
                if (!response.IsValid)
                    //errors, so copy the errors over to the ModelState
                    response.CopyErrorsToModelState(ModelState);
            }
 
            return Json(new[] { newItem }.ToDataSourceResult(request, ModelState));
        }
 
        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateAntiForgeryToken]
        public ActionResult AjaxServiceDelete([DataSourceRequest] DataSourceRequest request, ISmServiceDto itemToDelete, IDeleteSmService service)
        {
            if (itemToDelete != null)
            {
                var response = service.Delete(itemToDelete.SmServiceId);
                if (!response.IsValid)
                    //errors, so copy the errors over to the ModelState
                    response.CopyErrorsToModelState(ModelState);
            }
 
            return Json(ModelState.ToDataSourceResult());
        }

I must be doing wrong but I can't see it. Your help would be appreciated.

Jon Smith
Top achievements
Rank 1
 answered on 29 Apr 2013
14 answers
594 views
Hello,
can i make a custom razor helper that builds a kendo grid?
For example if i have
@(Html.Kendo().Grid<Namespace.ViewModels.TesttViewModel>()
.Name("Grid")

.Columns(columns =>
{
columns.Template(x => { }).ClientTemplate(
@"<a class='k-button' href='javascript: void(0)' onclick='doLoading(this)' style='min-width:32px!important'><span class='k-icon k-edit'></span></a>
<a class='k-button' href='javascript: void(0)' onclick='deleteRow(this);return false;' style='min-width:32px!important'><span class='k-icon k-delete'></span></a>"
).Width(100);

columns.Bound(p => p.Code).Title(Namespace.Resources.Resources.FieldText_TM_Code);
columns.Bound(p => p.Name).Title(UCMSPayroll.Resources.Resources.FieldText_TM_Name);
columns.Bound(p => p.MaxLength).Title(UCMSPayroll.Resources.Resources.FieldText_TM_MaxLength).Width(130);
columns.Bound(p => p.IsActive).ClientTemplate("<input type='checkbox' disabled='true' name='IsActive' #= IsActive ? checked='checked' : '' # />").Title(UCMSPayroll.Resources.Resources.FieldText_TM_IsActive);
columns.Bound(p => p.IsHour).ClientTemplate("<input type='checkbox' disabled='true' name='IsHour' #= IsHour ? checked='checked' : '' # />").Title(UCMSPayroll.Resources.Resources.FieldText_TM_IsHour);
columns.Bound(p => p.Precision).Title(UCMSPayroll.Resources.Resources.FieldText_TM_Precision);
columns.Bound(p => p.Priority).Title(UCMSPayroll.Resources.Resources.FieldText_TM_Priority);
columns.Bound(p => p.Formula).Title(UCMSPayroll.Resources.Resources.FieldText_TM_Formula);


})

.ToolBar(toolBar => toolBar.Template(@"<a id='addSome' class='k-button k-button-icontext k-grid-add' onclick='createRow()' href='javascript: void(0)'><span class='k-icon k-add'></span>add</a>
<span id='spanAdd' style='display:none;font-size:150%;margin-top:25px'><b>Add</b></span>
<span id='spanEdit' style='display:none;font-size:150%'><b>Edit</b></span>
<div style='float:right;color:black;font-size:150%'><b>measure</b></div>
"

))
.Pageable()
.Sortable()
.Scrollable()

.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.PkTallyMeasurement))
.Create(update => update.Action("EditingInline_Create", "Home"))
.Read(read => read.Action("EditingInline_Read", "Home"))
.Update(update => update.Action("EditingInline_Update", "Home"))
.Destroy(update => update.Action("EditingInline_Destroy", "Home"))
.PageSize(5)

)
)

so there is a lot of code,and i would like to use something like in the razor view:
@NameSpace.MyGrid(model)
and this should create all the above code that at least the portions that ar not changing such as the templates,the Pageable,Sortable,Datasource and so on.

Regards,
Daniel
Daniel
Top achievements
Rank 1
 answered on 29 Apr 2013
1 answer
191 views
Hi,
I have property i my viewmodel: Email with attribute: [Email(ErrorMessage = "not a valid email address")]
The attribute comes from DataAnnotationsExtensions.
The client error message shows up when using Server side binding but not when using Ajax.

How do I enable client side validation when using Ajax?

Regards,
Mattias
Daniel
Telerik team
 answered on 29 Apr 2013
1 answer
98 views
Hi.

I am using a Grid  with popup editing.

how can I hide the model.ID from the user in the popup?
Robert
Top achievements
Rank 1
 answered on 29 Apr 2013
Narrow your results
Selected tags
Tags
+133 more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?