0

I am creating a search page using ajax.

The scenario is: in our purchase system, user select the category from dropdownlist and then click browse button to show a modal form with a list of product based on selected category.

The problem is after the modal shown and then user fill criteria for searching and click Search, the categoryID is null. How to keep this value when we search data using ajax?

Below codes to represent what I've done so far:

Purchase View:

@using (Html.BeginForm("Create", "Invoice", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
    @Html.LabelFor(model => model.CategoryID, new { @class = "control-label col-md-2" })
    @Html.DropDownListFor(model => model.CategoryID, new SelectList(Model.Categories, "CategoryID", "Name"), "-- Please Select --", new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.CategoryID)

    @Html.LabelFor(model => model.ProductID, new { @class = "control-label col-md-2" })
    @Html.HiddenFor(model => model.ProductID)
    @Html.EditorFor(model => model.Product.Name, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
    <button class="btn btn-primary" id="btnLookupProduct" data-id="@Model.CategoryID" data-toggle="modal" data-target="#myModal">Lookup Product</button>
}

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">Product List</h4>
                @using (Ajax.BeginForm("Search", "Product", 
                    new AjaxOptions
                    { 
                        HttpMethod = "POST",
                        InsertionMode = InsertionMode.Replace,
                        UpdateTargetId = "lookup-timekeeper-container" 
                    }))
                {
                    @Html.DropDownList("FilterField",
                        new List<SelectListItem>
                        { 
                            new SelectListItem { Text = "Code", Value = "Code" },
                            new SelectListItem { Text = "Name", Value = "Name" }
                        },
                        "-- Please Select --",
                        new { @class = "form-control" })

                    @Html.TextBox("FilterValue", null, new { @class = "form-control", @placeholder = "Enter keyword" })

                    <input type="submit" value="Search" class="btn btn-primary" />
                }
            </div>
            <div class="modal-body" id="lookup-timekeeper-container">
                // list of product
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnLookupProduct").click(function () {
                var url = '@Url.Content("~/Product/Search/")' + $("#CategoryID").val();
                $.get(url)
                    .done(function (data) {
                        if (!data.message) {
                            $("#lookup-timekeeper-container").html(data);
                            $("#myModal").modal(show = true, backdrop = true);
                        } else {
                            alert(data.message);
                        }
                    });
            });
        });
    </script>
}

Purchase Controller:

public ActionResult Search(int? id, string filterField, string filterValue)
{
    var products = db.Products.Where(p => p.CategoryID == id);

    if (!string.IsNullOrEmpty(filterValue))
    {
        products = products.Where(filterField + ".Contains(@0)", filterValue);
    }

    return PartialView("_Lookup", products.ToList());
}

Product Partial Page:

@model List<PurchaseSystem.Models.Product>

<div class="table-responsive">
    <table class="table table-striped table-hover table-condensed">
        <tr>
            <th>Code</th>
            <th>Name</th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>@Html.DisplayFor(modelItem => item.Code)</td>
                <td>@Html.DisplayFor(modelItem => item.Name)</td>
            </tr>
        }
    </table>
</div>
RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
Willy
  • 1,689
  • 7
  • 36
  • 79
  • The ` –  Aug 20 '14 at 03:54
  • @StephenMuecke You're right, that's the problem, but I don't know how to solve it. I cannot move the categoryID to second form, since it is needed in first form before open the second form. – Willy Aug 20 '14 at 04:02
  • Add a `@Html.HiddenFor(model => model.CategoryID)` in second form and use `$('#btnLookupProduct').click(function(){ $('#secondForm #CategoryID').val($('#firstForm #CategoryID').val()); });` to set the `CategoryID` when Lookup Product button clicked. – cackharot Aug 20 '14 at 04:07
  • You can look at using the [form attribute](http://www.impressivewebs.com/html5-form-attribute/) to associate the dropdown with the second form, but my recommendation is to get rid of the `Ajax.BeginForm` rubbish and use jquery for that part (your already using it for the other function) –  Aug 20 '14 at 04:09
  • @cackharot I cannot add `@Html.HiddenFor(model => model.CategoryID)` in second form, it cause the is no data on category dropdownlist when page is first loaded. – Willy Aug 20 '14 at 04:28
  • @StephenMuecke form attribute is not working with IE, I'm using IE 9. btw, why I should remove `Ajax.BeginForm`? – Willy Aug 20 '14 at 04:37
  • Use '' instead. It will work – cackharot Aug 20 '14 at 04:45
  • Does not appear to work even in IE10 (suprise suprise!). Most of what of seen on SO relating to problems with `Ajax.BeginForm()` have been solved using jQuery, and when the gurus like [Darin Dimitrov](http://stackoverflow.com/questions/3840967/how-to-update-a-div-with-ajax-beginform-and-execute-a-javascript-function) recommend not using it I listen. [These answers](http://stackoverflow.com/questions/498680/pros-and-cons-of-ms-ajax-vs-jquery-in-an-asp-net-mvc-app) give few pros and cons. –  Aug 20 '14 at 04:50
  • @cackharot The categoryID is still null – Willy Aug 20 '14 at 05:42
  • you need to take the category value inside the hidden field and reassign on ajax post event to drop down this will help you – cracker Aug 20 '14 at 05:42
  • @cracker could you show me sample code? – Willy Aug 20 '14 at 05:44
  • you want category id only, that selected drop down value from the DropDownListFor right? do you want to use in the partial view also? – cracker Aug 20 '14 at 05:49
  • @cracker I want to keep CategoryID value from the selected dropdownlist. When the second form is first shown, the CategoryID is not null, and if I clicked Search then the CategoryID is null – Willy Aug 20 '14 at 05:53

1 Answers1

1

Take the value from Drop Down to HiddenField

<input type="hidden" value="" name="hiddens" id="hiddens" />

$("#btnLookupProduct").click(function () {
    var DropValues = $("#DROPDOWNID").val();
    document.getElementById("hiddens").value = DropValues;
});

Now on Click of Search Take this Hidden field value into the variable to use it

cracker
  • 4,900
  • 3
  • 23
  • 41
  • These are what I did: (1)I placed `` on the second form (2)Before `var url = '@Url.Content("~/Product/Search/")' + $("#CategoryID").val();` I Added `var categoryID = $("#CategoryID").val(); document.getElementById("hidCategoryID").value = categoryID;` and the categoryID is still null – Willy Aug 20 '14 at 06:25
  • one thing you need to put that in Purchase View , second you need to pass that value to public ActionResult Search() function with parameter and then you will find that into your partial view with mapping that again into the new hiddenfield in partial view – cracker Aug 20 '14 at 06:37
  • i.e @Html.Hidden("hiddenFFfData", somevarialfrompage) or @Html.HiddenFor(m => m.somevarialfrompage)) – cracker Aug 20 '14 at 06:43
  • OK I see. `@Html.Hidden` will not work, but `` will. Now it solved, thanks – Willy Aug 20 '14 at 07:06