Skip to content Skip to sidebar Skip to footer

Actionlink To Submit Model Value

I want my Ajax.ActionLink to pass a viewModel property to action. Here is my ViewModel public class ViewModel { public string Searchtext { get; set; } } My .cshtml

Solution 1:

In your code... you have 2 different ways of posting to the server: the link and the form button.

The problem is that the ActionLink has no way to get the value from the input in client side... just the original value.

If you press the Search button, you will see a value posted.

Now, you can use some jQuery to modify a standard ActionLink (not the Ajax.ActionLink): https://stackoverflow.com/a/1148468/7720

Or... you can transform your Form in order to do a Ajax post instead of a normal one: https://stackoverflow.com/a/9051612/7720

Solution 2:

I did this for a model of mine like so. I ONLY supported the HttpPost method. So add the HttpMethod="POST" to your Ajax.ActionLink

    [HttpPost]
    public ActionResult Accounts(ParametricAccountsModel model)
    {
        if (model.Accounts == null)
        {
            GetAccountsForModel(model);
        }
        if (model.AccountIds == null)
        {
            model.AccountIds = new List<int>();
        }
        return View(model);
    }

On the razor view

@Ajax.ActionLink(
        "Add Account to Order", "Accounts", "Parametric", null,
        new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "...", HttpMethod = "POST" },
        new { @id = "AddParametricAccountLink" })  

The model has a list of selected account ids. So in javascript, I modified the href of the action link dynamically.

function UpdateParametricAccountAction() {
    var originalLink = '/TradeNCashMgmt/Parametric/Accounts';
    varappend = '';
    var numberOfRows = $('#ParametricAccounts').find('.parametric-account-  row').size();
    for (var i = 0; i < numberOfRows; i++) {
        if (i != 0) {
            append += '&';
        }
        else {
            append = '?';
        }
        var idValue = $('#NotionalTransactionsAccountId_' + i).val();
        append += 'AccountIds%5B' + i + '%5D=' + idValue;
    }

    $('#AddParametricAccountLink').attr('href', originalLink + append);
}

Since the model binder looks for parameter names in the query string and form submission, it will pick up values using the href. So I posted a model object using the querystring on my Ajax.ActionLink. Not the cleanest method, but it works.

Post a Comment for "Actionlink To Submit Model Value"