Homer Tw
Homer Tw

Reputation: 95

Pasing Javascript result to View

I got a Question, I'm really new in working with Asp.net. I got a Javascript where I woult like to pass Data to my Controller.

<script type="text/javascript">
        $("#SearchButton").on("click", function () {
            var $sucheMoped = [];
            $("#tab_logic tbody tr")
                .each(function () {
                    var $Item = $(this);
                    var suchfeld = $Item.find("td > input[name='Suchfeld']").val();
                    var schluessel = $Item.find("td > select[name='Suchschluessel'] > option:selected").val();
                    alert(suchfeld + "&&&" + schluessel);
                    $sucheMoped.push({
                        Suchfeld: suchfeld,
                        Suchschluesseltyp: schluessel
                    });
                });
            window.open('@Url.Action("MainView","MainView")?SuchObject='+$sucheMoped);
        })
    </script>

I just would like to pass the "sucheMoped" from my javaScript to my Controller. My Controller is just expecting a IEnumarable of Objects with Properties Suchfeld and Suchschluesseltyp.

Anyone an idea?

Thanks Guys.

Upvotes: 2

Views: 259

Answers (3)

microsophtdeveloper
microsophtdeveloper

Reputation: 15

You can use jquery library $.getScript to call the action method in your controller and the return javascriptResult type in your action.

$.getScript("Home","Display")

// Home Controller
private JavaScriptResult Display()
{
    string message = "alert('Hello World');";

    return new JavaScriptResult { Script = message };
}

Upvotes: 0

gdyrrahitis
gdyrrahitis

Reputation: 5978

First of all, you need to change the way you invoke the controller action. You should stringify the array using the JSON.stringify() method.

So, this should look like this:

window.open('@Url.Action("MainView","MainView")?SuchObject='+JSON.stringify($sucheMoped));

Then, you need to create a custom model binder to bind your array with the action parameter. This is a simple array model binder for demonstration purposes only, it doesn't take into account failures or whatever, but it works in this scenario, passing the correct data, so please modify it to fit your needs.

public class ArrayModelBinder: DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var rawArray = controllerContext.HttpContext.Request.QueryString["SuchObject"];
        var array = JsonConvert.DeserializeObject<IEnumerable<MyObject>>(rawArray);

        return array;
    }
}

What I do here, is to get the query string submitted through the URL, convert it with JsonConvert.Deserialize<T> method and return it.

You simply need to decorate your parameter in the controller's action with the custom model binder, like this:

[HttpGet]
public ActionResult Search([ModelBinder(typeof(ArrayModelBinder))]IEnumerable<MyObject> SuchObject)
{
    return View(SuchObject);
}

Edit

window.open is useful if you want to open a new browser window. You could use it to open a new tab as well.

In order to navigate to another location without opening a new tab or window, use the window.location property like the following:

window.location = '@Url.Action("Search", "Home")?SuchObject=' + JSON.stringify(array);

Upvotes: 2

Georg Patscheider
Georg Patscheider

Reputation: 9463

If you use the jQuery.ajax method, you can pass complex objects as data parameter.

$.ajax({
    url: '@Url.Action("MainView", "MainView")',
    type: 'GET',
    data: { 'SuchObject': $sucheMoped },
    success: function (htmlContent) {
        // write content to new window (from http://stackoverflow.com/a/23379892/1450855)
        var w = window.open('about:blank', 'windowname');
        w.document.write(htmlContent);
        w.document.close();
    }
});

Upvotes: 0

Related Questions