0

A partial view (_AddItem.cshtml) is called from the main view (Category.cshtml) in order to add existing items to the page on load.

I'm now adding AJAX so that an item can be added, to the page, by the user at the click of a button. When the form is subsequently submitted the item will be added to the model.

The partial view relies on the category model (activeCategoryModel) and two variables. Currently, these are successfully being passed from the view in the following way:

Category.cshtml


@Html.Partial(
    "_AddItem", 
    activeCategoryModel, 
    new ViewDataDictionary(ViewData) { { "itemIndex", itemIndex }, { "itemLabel", itemLabel } }
);

My question is how can I pass the model (activeCategory) and these two variables when using AJAX? Below is the code I've started writing for the AJAX post:

Button and inputs added to view (Category.cshtml)


<input id="add-item-label" type="text" />
<input id="nextItemIndex" type="hidden" value="@activeCategoryModel.Items.Count" />
<button id="add-item" type="button">Add Item</button>

AJAX post added in javascript

This is not necessary fully functional code, I've just attempted to write an AJAX post with the variables in the 'data' parameter.


$("#add-item").click(function () {    
            var itemIndex = $("#nextItemIndex").val();  
            var itemLabel = $("#add-item-label").val();
            $.ajax({  
                type: "POST",  
                url: '@Url.Action("_AddItem")',  
                data: '{{itemIndex: ' + itemIndex + '}, {itemLabel: ' + itemLabel + '}}',  
                dataType: "json",  
                contentType: "application/json; charset=utf-8",  
                success: function () {  
                    $("#nextItemIndex").val($("#nextItemIndex").val() + 1);
                },  
                error: function () {  
                    alert("Error while adding item");  
                }  
            });  
            return false;  
        });  

Partial view call added to Controller

I think this is where the model and variables need to be included in the partial view call.


public ActionResult _AddItem(string itemIndex, string itemLabel)
        {
            
            return PartialView();
        }

Partial View (_AddItem.cshtml)

This has not been changed for the AJAX post.


@model CategoryModel

@{ int i = (int)ViewData["itemIndex"];}
@{ string l = (string)ViewData["itemLabel"];}

...

1 Answer 1

1

There are different ways in this case,

Example : Html.RenderPartial directly rendered partial action without ajax.

If you want to use Ajax to call partialView , you must be render Html. Because PartialView returned Html.

I think the most important value in Ajax request is dataType and the second important point is added returned html data in a div element

jQuery("#add-item").click(function () {
              var dItemIndex = 1; //$("#nextItemIndex").val();
              var dItemLabel = "Text"; // $("#add-item-label").val();

            $.ajax({
                type: "POST",
                url: '@Url.Action("_AddItem","Home")',
                data: { itemIndex: dItemIndex, itemLabel: dItemLabel },
                dataType: "html",
                //contentType: "application/json; charset=utf-8",
                success: function (d) {
                    console.log("Success");
                    $("#partialData").html(d);
                   **// Create div in cshtml Page
                   // <div id="partialData"></div>**

                },
                error: function () {
                    alert("Error while adding item");
                }
            });
            return false;
        });

At the controller side you can read parameters and fill in the content and send the PartialView as follows.

 public ActionResult _AddItem(string itemIndex, string itemLabel)
        {
            ViewData["itemIndex"] = itemIndex;
            ViewData["itemLabel"] = itemLabel;
            return PartialView(new CategoryModel { Id = 5, Text = "Sample 5" });
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much, the datatype, renaming the variables in the js, setting the viewdata in the controller and populating the div with the html on success.. all very helpful and this is now working.

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.