Archive of articles classified as' "C#"

Back home

Resharper & Entity Framework Generated Code

18/05/2011

Been looking for a way to get Resharper to ignore the code that is generated by Entity Framework for a while. Sure, I can ignore the entire project, but since we also had some repo/Unit Of Work implementations in the same project, that’s really not an option.

The final solution was to edit the code generating T4 (.tt) templates of Entity Framework to wrap the code in a custom region, i.e. ”EF Generated code”.

void BeginNamespace(string namespaceName, CodeGenerationTools code)
{
    CodeRegion region = new CodeRegion(this);
    if (!String.IsNullOrEmpty(namespaceName))
    {
#>
#region EF Generated Code //<- right here
namespace <#=code.EscapeNamespace(namespaceName)#>
{
<#+
        PushIndent(CodeRegion.GetIndent(1));
    }
}


void EndNamespace(string namespaceName)
{
    if (!String.IsNullOrEmpty(namespaceName))
    {
        PopIndent();
#>
}
#endregion //<- and here
<#+
    }
}

view raw generator.cs This Gist brought to you by GitHub.

Then tell Resharper to simply skip checking anything that is within region ”EF Generated Code” from ReSharper -> Options -> Generated Code

Done!

No Comments

MVC3 Ajax partial view validation

5/05/2011

Ran into a wall of trouble after getting Ajax to work properly in my previous post. Turns out that validation rules are not applied to partial views loaded with Ajax (Even when using the provided Ajax.ActionLink helper).

Thanks to this excellent blogpost http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/ i managed to work it out. But not until after bashing my head against the wall until numb.

The main problem was not so much the actual validation scripts, it was pretty clear to me that the validation rules would have to be rebuilt after injecting new objects into the DOM, but the fact that MVC refused to acually render the data-val / data-val-required properties for the elements that needed validating.

@using (Html.BeginForm("Create", "MyModel", FormMethod.Post, new { id = "CreateForm" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>MyModel</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Property)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Property)
            @Html.ValidationMessageFor(model => model.Property)
        </div>
     </fieldset>
}
view raw beginform.cs This Gist brought to you by GitHub.

These properties are usually rendered by Html.EditorFor / ValidationMessageFor when used as in the example above.

This is how it should look:

<input class="text-box single-line"
       data-val="true"
       data-val-required="This field is required!"
       id="Property"
       name="Property"
       type="text"
       value=""
/>
view raw proper.html This Gist brought to you by GitHub.

But when including a partial view through Ajax inside this outer form, the ability to use BeginForm inside that partial view is lost due to the fact that we can not have nested forms. And without BeginForm, no data-val properties :(

The key to getting the partial view to render the properties was to wrap the contents like the following code snippet:

@using(new MvcForm(ViewContext))
{
    <div class="editor-label">
        @Html.LabelFor(model => model.Property)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Property)
        @Html.ValidationMessageFor(model => model.Property)
    </div>

}
view raw partial.cs This Gist brought to you by GitHub.

And then to get the validation going, call xhalent’s brilliant js-function after appending the results of the Ajax request to the DOM.

$('#ajaxstuff').ajaxLink({
  data: {},
  success: function (data) {
    $('#ajaxdiv').append(data);
    $.validator.unobtrusive.parseDynamicContent('form');
  }
});
view raw js.js This Gist brought to you by GitHub.

8 Comments

Simple and painless Ajax in MVC3

27/04/2011

Even though Microsoft really came through with MVC3 and added a lot of sweetness, I still find myself reluctant to use the provided Ajax-functionality.

Here’s why:

@Ajax.ActionLink("Hurf", "Durf", "Controllurf",
  new { param = somestuff },
  new AjaxOptions {
    HttpMethod = "Post",
    OnSuccess = "Somejs"
  })

view raw donotwant.cs This Gist brought to you by GitHub.

This approach is nice and simple, yes. But what if I don’t like having global javascript functions all over the place to handle the results of the action. It kind of pains me to see that I can use ”unobtrusive” validation functionality in MVC3 but not unobtrusive Ajax handling.

This is solved by implementing the ”ajaxification” of a normal Html.ActionLink in a separate javascript,
such as proposed here http://stackoverflow.com/questions/4878127/mvc3-ajax-actionlink.

I needed a more reusable way of doing this, but portable enough to be painlessly lifted to other projects and easy to use for other developers in the project. So i slapped together this jQuery plugin…

(function($) {
  /**
* Ajaxify MVC3 ActionLinks
*
* @params {
* *success : result handling function(data, textStatus, jqXHR)
* *data : Data to send (accepts json data as default)
* verb : Http verb to use ('POST', 'GET', ..) Defaults to 'POST'
* type : dataType expected from server, Defaults to 'html'
* contentType : contentType sent TO server Defaults to 'application/json'
* error : error handling function(jqXHR, textStatus, errorThrown)
* }
*
*
* Usage:
* $('#ajaxstuff').ajaxLink({
* data: { foo: 'Fooinator' },
* success: function (data) { console.log(data); }
* });
*
*/
  $.fn.ajaxLink = function (params) {
    if (!params || !params.data || !params.success)
    throw new Error('ajaxLink parameters missing');

    //this is equal to $(this) in the current scope
    //save this reference for use inside nested scopes
    var link = this,

    //Defaults to type:html, verb:POST,
    //content: 'application/json'
    verb = params.verb || 'POST',
    type = params.type || 'html',
    contentType = params.contentType || 'application/json',

    //If contentType is set, do not assume json
    data = (params.contentType ? params.data : JSON.stringify(params.data));

    //Attach eventhandler to (this) link
    link.click(function () {
      $.ajax({
        url: params.url || link.attr('href'),
        type: verb,
        data: data,
        contentType: contentType,
        dataType: type,
        success: function (result, status, xhr) {
          params.success(result, status, xhr);
        },
        error: function (xhr, status, error) {
          if (params.error) params.error(xhr, status, error);
        }
      });

      //Stop the click from actually posting the page
      return false;
    });

   
  };

})(jQuery);
view raw ajaxlink.js This Gist brought to you by GitHub.

Using it is quite straightforward, or at least it seems to me at the time of writing this.

First, we create the controller action that we want to call with the Ajax link:

public ActionResult AjaxStuff(object foo) {
  var stuff = new { Name = "Stuff" + foo };

  ViewBag.Stuff = stuff.Name;

  return View();
}

This action returns a view, so a view will have to be created as well. A simple plain text partial view will do fine. Be sure not to load any layout for this though. The action could have returned JSON as well,
as both cases can be handled by the jQuery plugin.

With a controller action and a view in place, we create the ActionLink in the view where we need the Ajax functionality:

@Html.ActionLink("Click me!", "AjaxStuff", null,
  new { id = "ajaxstuff" })

There we go!, now we can declare all our events and handlers well outside the view layout as demonstrated in the following gist:

$('#ajaxstuff').ajaxLink({
  data: { foo: 'Fooinator' },
  success: function (data) {
    $('#ajaxdiv').html(data);
  }
});
view raw usage.js This Gist brought to you by GitHub.
No Comments