Generating form with hidden input and submitting t

2019-09-07 01:18发布

I thought this would be a lot simpler than it had been. I need to extract data from a cell in my datatable (Which I can do) and then submit it via a form with a hidden field in order to pass the variable to an action in my controller.

I am doing something similar to this prior in my code with the exception of generating the form.

I have tried different methods and not matter what when I access the collection in my action the value is null.

My View function:

$('#myTable').on('click', 'td', function () {
            var serial = table.cell(this).data();


            var form = $('<form action="@Url.Action("status")" id="hiddenform"><input type="hidden" id="serial" name="serial" value=""></form>').appendTo('body');
            $('.serial').val(serial);
            form.submit();


        });

and my controller I am parsing to:

//Accept GET and POST
    [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
    public ActionResult Status(System.Web.Mvc.FormCollection collection)
    {
        string serial = collection["serial"];

        if (serial == null || serial == "")
            System.Windows.Forms.MessageBox.Show("Error: Serial is NULL");

        return View(serial);
    }

To be honest I have butchered my code a lot in an attempt to fix this so it looks pretty awful.

Any help would be appreciated.

I am receiving the Error: Serial is NULL popup every time in my controller. However if I test the JQuery the value is not null it returns the correct value.

2条回答
Summer. ? 凉城
2楼-- · 2019-09-07 01:43

Your hidden field has a name and id property of serial, but the jQuery selector used to assign a value is looking for a class. Try # instead to select by ID:

$('#serial').val(serial);

Alternatively you can use jQuery to AJAX POST the data to your controller:

$.post( '@Url.Action("status")', { serial: table.cell(this).data() } );

And adjust your controller to expect a parameter of serial:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Status(string serial)
{
    if (serial == null || serial == "")
        System.Windows.Forms.MessageBox.Show("Error: Serial is NULL");

    return View(serial);
}
查看更多
等我变得足够好
3楼-- · 2019-09-07 01:53

Have you tried changing the method signature to the following?

public ActionResult Status(string serial)

where serial will be the parameter name that you will pass from the HTML form.

If the parameter name is blah in HTML, you might have to change your method signature to below:

public ActionResult Status(string blah)
查看更多
登录 后发表回答