3

Question background.

I have a view that contains a button that when clicked passes the contents of a 'p' tag and 'h3' tag. These tags are populated from a passed list of models from the corrosposnding controller.

I have an 'AddToCart' method on the controller that has the parameters passed to it from a Ajax JQuery function in the View.

The issue:

The following shows the JQuery Ajax call and the cshtml markup. Ideally I would like to pass the contents to the function. Currently I get the info from the tags based on their id's.

View Markup:

<h3 class="panel-title boldFeatures" id="name">@(Model.ElementAt(0).ProductName)</h3>

 <div class="panel-body">
      <img src="~/Images/LionToy.png" class="img-circle" id="featuresImages" alt="Work">
      <p>@(Model.ElementAt(0).ProductSummary)</p>
      <p id="qty">@(Model.ElementAt(0).productPrice)</p>

  @Html.ActionLink("Add To Cart", "AddToCart", null, new { id = "addToCart" }, new { @class = "btn btn-primary btn-block" })

The Ajax Function:

  <script>
    $("#addToCart").click(function (e) {

        e.preventDefault();
        $.ajax({
            url: '/HomePage/AddToCart',
            type: 'POST',
            data: { name: $('#name').val(), qty: $('#qty').val() },
        });
    });
    </script>

Controller AddToCart method:

 public void AddToCart(string name, string qty)
 {
    //Add to cart logic.
 }

Issue:

As shown the controller method is having both parameters passed as 'null'.

enter image description here

enter image description here

EDIT:

I have tried all of the suggestions below and still both of the parameters are being passed as 'null'.

2
  • you can check this answer, hope helps you stackoverflow.com/questions/10757001/… Commented Nov 26, 2014 at 22:23
  • All you need is to use text() instead of val() If that not working as you indicated in other (correct) answers then there is other issues here. One might be the strange use of Model.ElementAt(0).ProductSummary Are you rendering this from a collection (i.e. you are repeating the above code with Model.ElementAt(1)... etc. in which case you have invalid html and you need to change this html and use relative selectors (not a hack) Commented Nov 29, 2014 at 4:12

7 Answers 7

2
+150

Quite a few things are funky in this code, so I'm going to post something you can literally copy-paste into a new mvc project and it will work straight away:

Try this:

View Code:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $("#addToCart").click(function (e) {
            e.preventDefault();
            alert($(this).data("name"));
            $.ajax({
                url: '@Url.Action("AddToCart")',
                type: 'POST',
                data: { name: $(this).data("name"), qty: $(this).data("quantity") },
            });
        });
    });
</script>

<h3 class="panel-title boldFeatures" id="name">@(Model.ElementAt(0).ProductName)</h3>

<div class="panel-body">
    <img src="~/Images/LionToy.png" class="img-circle" id="featuresImages" alt="Work">
    <p>@(Model.ElementAt(0).ProductSummary)</p>
    <p id="qty">@(Model.ElementAt(0).ProductPrice)</p>

        <input type="button" data-name="@Model.ElementAt(0).ProductName" data-quantity="@Model.ElementAt(0).Quantity" value="Add to Cart" id="addToCart" />
</div>

In the Controller:

    public void AddToCart(string name, string qty)
    {
        //Add to cart logic.
        string qname = name + qty; //put a breakpoint here and you'll see name is populated.
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Many thanks C Bauer this has finally sorted my issue. I will award you the bounty in 22 hours time when SO will allow me! Again many thanks!.
Happy to help my friend!
@user1352057, What is it you do not understand about having invalid html?
2

h3 and paragraph have text content not value. change your ajax call to

data: { name: $('#name').text(), qty: $('#qty').text() },

2 Comments

thanks for your reply. I have tried using the .text() method and it still is passing null's
if you put a breakpoint in your script what is the value of $('#name').text() on the view?
2

Are you sure your jquery is being called? Try using this and seeing if the values are still null:

@Html.ActionLink("Add To Cart", "AddToCart", new { name = Model.Name, qty = Model.Quantity}, new { id = "addToCart" }, new { @class = "btn btn-primary btn-block" })

I assume what you want to do here is this:

http://api.jquery.com/data/

Add data attributes to link:

 @Html.ActionLink("Add To Cart", "AddToCart", null, new { id = "addToCart", data-name = "@Model.Name", data-quantity="@Model.Quantity" }, new { @class = "btn btn-primary btn-block" })

Access them in the script:

  <script>
    $("#addToCart").click(function (e) {

        e.preventDefault();
        $.ajax({
            url: '/HomePage/AddToCart',
            type: 'POST',
            data: { name: $(this).data("name"), qty: $(this).data("quantity") },
        });
    });
    </script>

4 Comments

This would be the cleanest way to do what needs done. The link already has access to the Name and Quantity - why complicate it by having jQuery append it to the data set?
@C Bauer Thanks for your reply. This does indeed work but returns an empty view. The reason I'm using the Ajax method is so I can POST the data to the AddToCart method and not have the blank view issue. If there is a way I can do this without getting a blank view returned using ActionLink it would be great to know.
I've been racking my brain on the best way, and the only thing I can come up with is to add two data attributes on to your button that contains the model name and quantity and call $(this).data("name") and $(this).data("quantity").
@C Bauer thanks again for your input. Sadly this still hasn't solved the issue.
1

You should use text() and not val(). h3 and p tags have text and not value. So

$.ajax({
        url: '/HomePage/AddToCart',
        type: 'POST',
        data: { name: $('#name').text(), qty: $('#qty').text() },
    });

Comments

1

Remove the last comma after the data object and use text() try

<script>
$("#addToCart").click(function (e) {
    e.preventDefault();
    $.ajax({
        url: '/HomePage/AddToCart',
        type: 'POST',
        data: { name: $('#name').text(), qty: $('#qty').text() }
    });
});
</script>

1 Comment

thanks for your reply. .text() still passes 'nulls'.
1

Well, you can't just get val form non-input elements. As you have no inputs, try using html instead. (though, it's strange that text is not working. Do you have any values there at all?)

$("#addToCart").click(function (e) {
    e.preventDefault();
    $.ajax({
        url: '/HomePage/AddToCart',
        type: 'POST',
        data: { name: $('#name').html(), qty: $('#qty').html() }
    });
});

Alternatively you can put hidden inputs in your html and get their values:

<input type="hidden" id="name-hidden" value="@(Model.ElementAt(0).ProductName)" />
<input type="hidden" id="qty-hidden" value="@(Model.ElementAt(0).productPrice)" />

and then use val in your javascript

$("#addToCart").click(function (e) {
    e.preventDefault();
    $.ajax({
        url: '/HomePage/AddToCart',
        type: 'POST',
        data: { name: $('#name-hidden').val(), qty: $('#qty-hidden').val() }
    });
});

Comments

0

As others have said, you should be using .text() instead of .val().

Also, we're assuming that the values are being correctly populated from your ViewBag data.

If that data is being populated in your p and h3 tags with those ids, this code should work. One thing you could try is passing them as querystring params:

$.ajax({
    url: '/HomePage/AddToCart?name=' + $('#name').text() + '&qty=' + $('#qty').text(),
    type: 'POST'
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.