I want to have a way to get an idea, to focus on a specific property of the model from the controller in a general way.
What I still have:
Controller:
View
public static class ViewPageExtensions { public static MvcHtmlString FocusScript<TModel>(this ViewPage<TModel> viewPage) { if (viewPage.ViewData["FieldToFocus"] != null) { return MvcHtmlString.Create( @"<script type=""text/javascript"" language=""javascript""> $(document).ready(function() { setTimeout(function() { $('#" + viewPage.Html.IdFor((System.Linq.Expressions.Expression<Func<TModel, object>>)viewPage.ViewData["FieldToFocus"]) + @"').focus(); }, 500); }); </script>"); } else { return MvcHtmlString.Empty; } } }
The problem I am facing right now is that in the FocusScript
view FocusScript
I don’t know the return type of the property to focus on, and casting to (System.Linq.Expressions.Expression<Func<TModel, object>>)
does not executed for any property that does not return an object.
I can’t just add a second general parameter for the property, because I don’t know what type of return property the controller wants to focus on me on.
How can I write a FocusScript
extension FocusScript
in general so that it can be used with the properties of variables of return types?
Why is there a problem?
I know that I can just pass the identifier of the control that I want to focus on in the controller, and have javascript reading that identifier, find the control and focus on it. However, I do not like to have what belongs in the view (control Id) hardcoded in the controller. I want to tell the method which property I want, and it should know that Id is used in the same way that a view usually gets / creates an Id for a control.
Let's say I have a model:
class MyModel { public int IntProperty { get; set; } public string StringProperty { get; set; } }
In different places of the controller I want to focus one other field:
FocusOnField((MyModel m) => m.IntProperty); ... FocusOnField((MyModel m) => m.StringProperty);
Now in the first case, the expression is a function that returns an integer, in the second case, it returns a string. As a result, I don’t know how to distinguish my ViewData ["FieldToFocus"] before (pass it to IdFor<>()
), since it depends on the property.