Dan
Dan

Reputation: 29365

What is the best way to write a form in ASP.NET MVC?

What is the the best way to write a form to submit some data in ASP.NET MVC? Is it as Scott Guthrie demonstrates here? Are there better approaches? Perhaps with less using of strings?

alt text

Upvotes: 4

Views: 760

Answers (1)

ollifant
ollifant

Reputation: 8616

I don't really like strings in my code, as it isn't possible to refactor. A nice way is to use Linq Expressions. If you get passed a model as ViewData you can use the following statement:

<%= ShowDropDownBox(viewData => viewData.Name); %>
...

public static string ShowDropDownList<T>(this HtmlHelper html, Expression<Action<T>> property)
{
    var body = action.Body as MethodCallExpression;
    if (body == null)
        throw new InvalidOperationException("Expression must be a method call.");
    if (body.Object != action.Parameters[0])
        throw new InvalidOperationException("Method call must target lambda argument.");
    string propertyName = body.Method.Name;
    string typeName = typeof(T).Name;

    // now you can call the original method
    html.Select(propertyName, ... );
}

I know the original solution is performing faster but I think this one is much cleaner.

Hope this helps!

Upvotes: 2

Related Questions