Search code examples
asp.net-mvcrazorrazor-declarative-helpers

ASP.NET MVC helper js function not working in Razor 4


I have the following razor helper functions in a cshtml file, it works at asp.net mvc 3, after I migrate it mvc 4, it's not working (compiling) any more.

The purpose of the major function PopulateForm is to set values of html controls according to a server model.

I figured out it's because of the syntax at line:

@(SetField(formId, fieldNamePrefix + p.Name, value));

so I changed it to:

@Js.SetField(formId, fieldNamePrefix + p.Name, value);

it compiles but if I debug it, it's not executing the body of SetField function.

@using System.Linq;

@helper Encode(object value) {
    @(value != null ? HttpUtility.JavaScriptStringEncode(value.ToString()) : "")
}


@helper SetField(string formId, string fieldName, object value) {
    var type = (value != null) ? value.GetType() : typeof(object);
    var formattedValue = value;
    if (type == typeof(DateTime)) { formattedValue = ((DateTime)value).ToString("dd-MMM-yyyy"); }
    if (type == typeof(TimeSpan)) { formattedValue = ((TimeSpan)value).ToString("hh\\:mm"); }
    @: $("#@formId *[name='@fieldName']").changeVal("@JS.Encode(formattedValue)");
}


@helper PopulateForm(dynamic model, string formId, string[] excludedFields = null, string fieldNamePrefix = "") {
    var valueProperties = model.GetType().GetProperties();
    foreach (var p in valueProperties)
    {
        if (excludedFields != null && Array.Exists<string>(excludedFields, f => f == p.Name)) { continue; };
        var value = @p.GetValue(model, null);
        @(SetField(formId, fieldNamePrefix + p.Name, value));
    }
}

Solution

  • Try writing it this way:

    @using System.Linq;
    
    @helper Encode(object value) {
        @(value != null ? HttpUtility.JavaScriptStringEncode(value.ToString()) : "")
    }
    
    
    @helper SetField(string formId, string fieldName, object value) {
        var type = (value != null) ? value.GetType() : typeof(object);
        var formattedValue = value;
        if (type == typeof(DateTime)) { formattedValue = ((DateTime)value).ToString("dd-MMM-yyyy"); }
        if (type == typeof(TimeSpan)) { formattedValue = ((TimeSpan)value).ToString("hh\\:mm"); }
        @: $("#@formId *[name='@fieldName']").changeVal("@Encode(formattedValue)");
    }
    
    
    @helper PopulateForm(dynamic model, string formId, string[] excludedFields = null, string fieldNamePrefix = "") {
        var valueProperties = model.GetType().GetProperties();
        foreach (var p in valueProperties)
        {
            if (excludedFields != null && Array.Exists<string>(excludedFields, f => f == p.Name)) { continue; };
            var value = p.GetValue(model, null);
            SetField(formId, fieldNamePrefix + p.Name, value);
        }
    }