Recognize particular id in ajax form mvc3 from sev

2019-08-24 07:25发布

问题:

I am currently working on a MVC3 project. I currently stuck on this portion.

I have this Ajax form which contains several hyperlink

@using (Ajax.BeginForm("Click", new AjaxOptions { UpdateTargetId = "showpage" }))
{
     <a href="#" id="0" onclick='document.forms[0].submit()'>Link 0</a>
     <a href="#" id="1" onclick='document.forms[0].submit()'>Link 1</a>
}

I have this function called "Click" in a controller to fire whenever there'a link clicked.

public ActionResult Click(String id)
{
   // Action here
}

However, Whenever I click one of the hyperlinks, the click function receive id as "null". I want the function to know which hyperlink is click when enter the controller. Help needed :(

回答1:

From my understanding, I think you're after something like this:

HTML:

    <div id="showpage">
    </div><br />
    @using (Ajax.BeginForm("Click", "", new AjaxOptions { UpdateTargetId = "showpage" }, 
               new { @id = "myAjaxForm" }))
    {
        @Html.ActionLink("Link 0", "Click", null, new { @id = "Link0", @data_val = "0", @class = "links" })
        @Html.ActionLink("Link 1", "Click", null, new { @id = "Link1", @data_val = "1", @class = "links" })
        @Html.Hidden("id", "");
    }

SCRIPT:

<script>
    $(function () {
        $('a[class=links]').click(function (e) {
            e.preventDefault();
            $("input#id").val($(this).attr("data-val"));
            $('form#myAjaxForm').submit();
        });
    });
</script>

CONTROLLER:

    public ActionResult Click()
    {
        var m = new MyModel();
        return View(m);
    }

    [HttpPost]
    public ActionResult Click(string id)
    {
        return Content("ID = " + id, "text/html");
    }

Hope this helps



回答2:

I would recommend you to use a separate forms per button (which contrary to classic WebForms is something that you should not be afraid of in ASP.NET MVC) and of course use submit buttons instead of hyperlink which are the semantically correct element to submit a form:

@using (Ajax.BeginForm("Click", new { id = "0" }, new AjaxOptions { UpdateTargetId = "showpage" }))
{
    <button type="submit" value="Link 0" />
}

@using (Ajax.BeginForm("Click", new { id = "1" }, new AjaxOptions { UpdateTargetId = "showpage" }))
{
    <button type="submit" value="Link 1" />
}

Now inside your Click action you will get the correct id.



回答3:

Instead of hyperlinks you can use submit buttons with the name property.

@using (Ajax.BeginForm("Click", new AjaxOptions { UpdateTargetId = "showpage" }))
{
   <input type="submit" name="action" value="0" />
   <input type="submit" name="action" value="1" />
}

public ActionResult Click(string action, ... )
{
   // Action here
}