简体   繁体   中英

Passing a parameter to Action method

I have an action method like this

public JsonResult Create(Product p, string extra)

The view is bound to @model Product

On calling Create action via ajax call, I am getting Product P values from the form but extra is always null, although extra is in the same form

<input type="text" name="extra" />

I also tried Request.Form["extra"] it was null too. What I am missing? how to get value of input[name=extra] in action method?

You didn't mention how are you calling this action (other than saying AJAX which obviously is not enough), so assuming you have an HTML form representing a product and an input field containing some extra value:

@model Product
@using (Html.BeginForm())
{
    @Html.EditorForModel()

    <input type="text" name="extra" value="some extra value" />

    <input type="submit" value="Create" />
}

you could unobtrusively AJAXify this form like this:

$('form').submit(function() {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function(result) {
            // TODO: handle the results of the AJAX call
        }
    });
    return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM