Search code examples
asp.net-mvckendo-asp.net-mvc

Kendo own extension-method


How would I define my own extension-method that wraps Kendo's HtmlAttributes? I want to add bool parameter and only calls HtmlAttributes if @item.isRequired is true?

 @(Html.Kendo().RadioGroupFor(m => m.MeetingPollingQuestions)
      .Name(string.Format("PollingResponses[{0}].Value", idx))
      .HtmlAttributes(new { required = "required", data_val_required = "Question is 
      Required" })
        .Items(i=>
           {
              foreach (var option in @item.RadioButtonList)
                 i.Add().Label(option.Label).Value(option.Value);
              })
         .Value("Value")
       )
 }

Solution

  • You could create a variable in your razor file to store the value for HtmlAttributes.

    @{
      var htmlAttributesData = item.isRequired ? "new { required = "required", data_val_required = "Question is Required" }" : "";
    }
    

    Your RadioGroupFor should look like this after:

    @(Html.Kendo().RadioGroupFor(m => m.MeetingPollingQuestions)
          .Name(string.Format("PollingResponses[{0}].Value", idx))
          .HtmlAttributes(htmlAttributesData)
            .Items(i=>
               {
                  foreach (var option in @item.RadioButtonList)
                     i.Add().Label(option.Label).Value(option.Value);
                  })
             .Value("Value")
           )
     }