Recognize particular id in ajax form mvc3 from sev

2019-08-24 06:56发布

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 :(

3条回答
Bombasti
2楼-- · 2019-08-24 07:12

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
}
查看更多
Summer. ? 凉城
3楼-- · 2019-08-24 07:19

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.

查看更多
放荡不羁爱自由
4楼-- · 2019-08-24 07:29

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

查看更多
登录 后发表回答