Question: I'm using Ajax to Post to the controller in Mvc but my var resets to null in the foreach

Question

I'm using Ajax to Post to the controller in Mvc but my var resets to null in the foreach

Answers 1
Added at 2016-12-25 11:12
Tags
Question

So Im using this code to fill my container with Posts from the database.

The problem is during the foreach im adding a ID to the onclick for the Like Function. But when I try and use it it has turned into a null. Even though the call stack on chrome claims its not null. Does anyone have a clue on how to solve this?

Html:

    @using (Html.BeginForm())
    {
        foreach (Contribution ctrib in Model)
        {
            <p>@ctrib.Message.Content @ctrib.Likes @ctrib.Reports</p>
            int TempID = ctrib.ID;
            <a name="link" href="#" onclick="javascript:Like(@TempID);">Like</a>
        }
    }

Javascript:

<script type="text/javascript">
function Like(link) {

    var MyAppUrlSettings = {
        MyUsefulUrl: '@Url.Action("Like", "TimelinePage")'
    }
    $.ajax({
        type: "POST",
        url: MyAppUrlSettings.MyUsefulUrl,
        data: link,
        dataType: "json"
    });
}

Controller:

    [HttpPost]
    public void Like(int ID)
    {
            Contribution C = new Contribution(ID);
            C.likePost();
            RedirectToAction("TimelinePage");

    }
Answers
nr: #1 dodano: 2016-12-25 11:12

You can directly use like this

@using (Html.BeginForm())
{
    foreach (var ctrib in Model)
    {
        <p>@ctrib.Message.Content @ctrib.Likes @ctrib.Reports</p>
        <a name="link" href="#" onclick="javascript:Like('@ctrib.ID');">Like</a>
    }
}

and your javascript code :

function Like(link) {
    jQuery.ajax({
        url: '@Url.Action("Like", "TimelinePage")',
        method: "POST",
        cache: false,
        data: { Id: link }
    }).done(function (result) {
         alert(result); 
    });
}
Source Show
◀ Wstecz