Search code examples
asp.netjqueryasp.net-mvc-2viewcontrollers

MVC2 and two different models using same controller method? Possible?


I don't know if this is the right way of doing this or not, but I am using Jquery and MVC2. I am using a the $.ajax method to make a call back to a controller to do some business logic on a .blur of a textbox.

I have two views that basically do the same thing with the common data, but are using different models. They both use the same controller. It might be easier to explain with code:

So here are the two models:

public class RecordModel {
    public string RecordID { get; set; }
    public string OtherProperties { get; set; }
}

public class SecondaryModel {
    public string RecordID { get; set; }
    public string OtherPropertiesDifferentThanOtherModel { get; set; }
}

There are two views that are strongly typed to these models. One is RecordModel, the other SecondaryModel.

Now on these views is a input="text" that is created via:

<%= Html.TextBoxFor(model => model.RecordID) %>

There is jQuery javascript that binds the .blur method to a call:

<script>
    $('#RecordID').blur(function() {
        var data = new Object();
        data.RecordID = $('#RecordID').val();
        // Any other stuff needed

        $.ajax({
            url: '/Controller/ValidateRecordID',
            type: 'post',
            dataType: 'json',
            data: data,
            success: function(result) {
                 alert('success: ' + result);
            },
            error: function(result) {
                 alert('failed');
            }
         });
      }
 </script>

The controller looks like:

[HttpPost]
public ActionResult ValidateRecordID(RecordModel model) {
    // TODO: Do some verification code here

    return this.Json("Validated.");
}

Now this works fine if I explicitly name the RecordModel in the controller for the View that uses the RecordModel. However, the SecondaryModel view also tries to call this function, and it fails because it's expecting the RecordModel and not the SecondaryModel.

So my question is this. How can two different strongly typed views use the same Action in a controller and still adhering to the modeling pattern? I've tried abstract classes and interfaces (and changing the view pages to use the Interface/abstract class) and it still fails.

Any help? And sorry for the robustness of the post...

Thanks.


Solution

  • You could define an interface for those classes.

    interface IRecord
    {
        string RecordID { get; set; }
        string OtherProperties { get; set; }
    }
    

    and make the method receive the model by using that:

    [HttpPost]
    public ActionResult ValidateRecordID(IRecord model) 
    {
        // TODO: Do some verification code here
    
        return this.Json("Validated.");
    }