admin管理员组

文章数量:1404461

I am loading packages using for-each loop, clearly from code.....

<div class="row">             
  @foreach(var items in ViewBag.packages)
  {  
    <div class="col-md-2">
      <div class="price-table-area">
        <div class="fixed-img sec-bg5"></div>
        <ul class="proce-table">
          <li class="price-prdct"><i>$</i>@items.NewPrice<i>/m</i></li>
          <input type="submit" class="submit" value="SignUp" onclick="packageSelect(@ViewBag.PackageId)">
        </ul>
      </div>
    </div>
  }
</div>

I am calling function packageSelect on click which invokes ajax call to controller action. As can be seen that I am passing @viewbag.PackageId parameter to function.

Controller action

public ActionResult SelectPackage(int PackageId)
{
    Session["Package"] = PackageId;
    return this.Json(string.Empty); ;
}

Script

<script>
  function packageSelect(PackageId) {
    $.ajax({
      type: "POST",
      url: '@Url.Action("SelectPackage", "Home")',
      dataType: "JSon",
      data: { "PackageId": PackageId },
      success: function (data) {
        console.log(data);
        // $("#SecondInfo").focus({ scrollTop: "0px" });
        $('html, body').animate({ scrollTop: $('#contact-us').offset().top }, 'slow');
      },
      error: console.log("it did not work"),
    });
  };
</script>

Is it right way to call like that? The problem is function not called.

I am loading packages using for-each loop, clearly from code.....

<div class="row">             
  @foreach(var items in ViewBag.packages)
  {  
    <div class="col-md-2">
      <div class="price-table-area">
        <div class="fixed-img sec-bg5"></div>
        <ul class="proce-table">
          <li class="price-prdct"><i>$</i>@items.NewPrice<i>/m</i></li>
          <input type="submit" class="submit" value="SignUp" onclick="packageSelect(@ViewBag.PackageId)">
        </ul>
      </div>
    </div>
  }
</div>

I am calling function packageSelect on click which invokes ajax call to controller action. As can be seen that I am passing @viewbag.PackageId parameter to function.

Controller action

public ActionResult SelectPackage(int PackageId)
{
    Session["Package"] = PackageId;
    return this.Json(string.Empty); ;
}

Script

<script>
  function packageSelect(PackageId) {
    $.ajax({
      type: "POST",
      url: '@Url.Action("SelectPackage", "Home")',
      dataType: "JSon",
      data: { "PackageId": PackageId },
      success: function (data) {
        console.log(data);
        // $("#SecondInfo").focus({ scrollTop: "0px" });
        $('html, body').animate({ scrollTop: $('#contact-us').offset().top }, 'slow');
      },
      error: console.log("it did not work"),
    });
  };
</script>

Is it right way to call like that? The problem is function not called.

Share Improve this question edited Jun 19, 2015 at 4:09 user3559349 asked Jun 18, 2015 at 11:15 Suhail Mumtaz AwanSuhail Mumtaz Awan 3,4838 gold badges47 silver badges77 bronze badges 13
  • Don't you need an @ in front of the foreach? Is that a typo in your post? – BJ Safdie Commented Jun 18, 2015 at 11:22
  • 1 Far better these days to use unobtrusive javascript and avoid polluting your mark-up with behavior. Add the PackageId as a data- attribute and use $('.yourClassName').click(function() { var id = $(this).data('packageId'); ...}); – user3559349 Commented Jun 18, 2015 at 11:31
  • 1 @SuhailMumtazAwan, Was your last ment in response to mine? (not sure what your referring to). And as others have noted, you need to change the input to a button with type="button", or include return false; in the script or both the ajax call and the normal submit will occur – user3559349 Commented Jun 18, 2015 at 11:38
  • 1 @SuhailMumtazAwan, You noted your getting a 500 error. That's usually the result of an exception being thrown on the server (or specifying the wrong dataType). You can use you browser tools (Network Tab) to inspect the details) – user3559349 Commented Jun 18, 2015 at 11:52
  • 1 @SuhailMumtazAwan, If your using jquery v1.9+ then return Json(string.Empty) may throw that exception. Test this by using (say) return Json("success"); – user3559349 Commented Jun 18, 2015 at 13:22
 |  Show 8 more ments

4 Answers 4

Reset to default 3

In all the seriousness, I don't think this is a good way to do this.

Instead you should approach to it more clearer-

Use data attributes.

<button class="submit" data-id="@items.PackageId">SignUp</button>

And then-

$('button').on('click',function(){
    var id = $(this).data('id'); //attribute's value
    packageSelect(id); //passing the value to function
});

P.S.- Also I suppose you are iterating the id, If yes then you shouldn't have used it as -

@ViewBag.PackageId

It should be (if its iterating and not going to stay the same)- @items.PackageId

Your input is of submit type change its type to button. So when you click the button form will be posted and onclick will notfire.

<input type="button" class="submit" value="SignUp"
                            onclick="packageSelect(@ViewBag.PackageId)">

I don't think click accepts parameters that way. Try

<input type="submit" class="submit" value="SignUp"
      onclick="function(){packageSelect(@ViewBag.PackageId);}">

I also agree with Mairaj that the type='submit' is suspicious.

Why do you need to pass PackageId value from ViewBag to the function packageSelect? If you are just passing the value to contoller action using ajax call, then I think it can be directly accessed in the action method from ViewBag.

And if you are making ajax call to another controller action then, There is TempData collection you can use to store PackageId.

本文标签: javascriptHow to call onclick jquery function having dynamic dataAspnet Mvc5Stack Overflow