Click here to Skip to main content
15,936,119 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi
I am new to MVC. I have written very basic MVC Application. All it does at the moment is get the values from form through controller and save them in database. [Insert Operation of application].

I am trying to create Update Operation.

TASK
I have displayed a dropdown list populated with product name [display text] and product ID[value]. On the same page is the field productCode [text box].
When a user selects a value from dropdown, I want to populate code value [retrieving it from db based on productID]

VIEW
JavaScript
<script type="text/javascript">
    $(document).ready(function () {
        $("#ProductList").click(function () {
            $.ajax({
                url: '@Url.Action("GetProductData", "Home")',
                type: 'POST',
                dataType: 'json',
                data: { clientID: $("#ProductList").val() },
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    if (data.success) {
                        // fill the product code
                        $("#ProductCode").val(data.ProductCode);
                    }
                    else {
                        // show a message in a alert or div
                        alert('This Product ID is not valid. Try again!');
                    }
                }
            });
        });
    });

    
</script>

@{
    ViewBag.Title = "Update Product";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm("UpdateExistingProduct", "Home", FormMethod.Post))
{
    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js">

    </script>
    <table>
        <caption style="text-align:left"><h3>@ViewBag.Message</h3></caption>
        <tr>
            <td>Please select Product</td>
            <td>@Html.DropDownList("ProductList", null, new {id="ProductList"})</td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>@Html.Label("Code")</td>
            <td>@Html.TextArea("ProductCode", null, new {@readOnly = "readonly"})</td>
        </tr>
    </table>
}

CONTROLLER
C#
[HttpPost]
public ActionResult GetProductData(string productID)
{
    Product prd = Product.GetProduct(Convert.ToInt32(productID));
    if (prd != null)
    {
        return Json(new { success = true, productCode = prd.ProductCode});
    }
    return Json(new { success = false });

}


NOTE: I Found Jquery Code on website and there it was mentioned that code is working. In my case nothing happens.
Can anyone please help me?

Regards
Posted
Updated 10-Apr-13 4:19am
v2
Comments
Prasad Khandekar 10-Apr-13 10:27am    
Do you see any errors in browser? You should be using onChange handler instead of onClick.
Abdul Muneeb Abbasi 10-Apr-13 10:30am    
I have tried onChange. that did not work. I have tried change method. that did not work and no errors in explorer
Prasad Khandekar 10-Apr-13 11:03am    
Try Firefox with HttpFox plugin to check whether AJAX POST request is going or not.

Hello,

Please see this[^] thread. I think it contains the solution for your problem.

Change line which reads as
JavaScript
$("#ProductList").click(function () {
TO
JavaScript
$("#ProductList").change(function () {


Here is the sample of how your javascript might look like.
Javscript
$(document).ready(function() {
    $('#ProductList').change(function() {
        var str = this.options[this.selectedIndex].value;
        $.ajax('@Url.Action("GetProductData", "Home")', {
            type: 'POST',
            dataType: 'json',
            data : {'productID': str }.
            success: function(data, status, jqXHR) {
                if ("success" === status) {
                    document.getElementById('#ProductCode').value = data.ProductCode;
                } else {
                    alert('This Product ID is not valid. Try again!');
                }
            }
        });
    });
});

Regards,
 
Share this answer
 
v3
Comments
Abdul Muneeb Abbasi 11-Apr-13 10:24am    
View - Script
<script type="text/javascript">
$(document).ready(function () {
$("#ProductList").change(function () {
var f = $("form");
f.submit(function () {
var productData = f.serialize();
$.post(f.attr("action"), productData, function (result, status) {
if (result !== null) {
$("#productCode").text(result.ProductCode);
}
else {
alert('Invalid ID');
}
});
});
});
});


</script>

Controller
public JsonResult GetProductData(int productID)
{
Product product = Product.GetProduct(productID);
if (product != null)
{
return Json(new { product });
}
return Json(new { product });

}


NOT WORKING
Can any one help me please?
Prasad Khandekar 11-Apr-13 10:54am    
Hello No need to write f.submit function. Use following portion from your earlier code.

$.ajax({
url: '@Url.Action("GetProductData", "Home")',
type: 'POST',
dataType: 'json',
data: { clientID: $("#ProductList").val() },
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.success) {
// fill the product code
$("#ProductCode").val(data.ProductCode);
}
else {
// show a message in a alert or div
alert('This Product ID is not valid. Try again!');
}
}
});

I am assuming that this script is located in the View Template. Check the final HTML code in browser and see wherther the value for URL attribute is getting rendered properly.
Member 15404679 10-Feb-22 2:52am    
jh
Abdul Muneeb Abbasi 11-Apr-13 12:02pm    
Ok Little bit success there are two problems in it now
1. I had to remove argument from controller. I tried with hardcoded value and controller returns the proper code.
2. I debugged through Internet Explorer development tools. I am retrieving value in view side but it is not renderred in the text field.

any suggestions
Prasad Khandekar 11-Apr-13 14:54pm    
Hello,

Try using document.getElementById('ProductCode').value = data.ProductCode; As far as passing parameter to ActionMethod just change the parameter name ion ajax call to productID. It should work (See Automaticall Mapping Parameters Section [http://msdn.microsoft.com/en-us/library/dd410269(v=vs.98).aspx]).

Regards,

Regards,
I found the solution. and it is working perfectly.

Here is that JQUERY code.
C#
<script type="text/javascript">
    $(document).ready(function () {
        $("#ProductList").change(function () {
            var selectedProductID = { productID: $("#ProductList").val() };
            $.ajax({
                url: '@Url.Action("GetProductData", "Home")',
                type: 'Post',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(selectedProductID),
                success: function (data) {
                    if (data.success) {
                        document.getElementById("ProductName").value = data.productName;
                    }
                    else {
                        alert('invalid ID' + data.success);
                    }
                }
            });
        });
    });
</script>


CONTROLLER CODE
C#
[HttpPost]
public JsonResult GetProductData(string productID)
{
    Product product = Product.GetProduct(Convert.ToInt32(productID));
    if (product != null)
    {
        return Json(new { success = true, productName = product.ProductName});
    }
    return Json(new { success = false });

}


I still do not know what is the difference but atleast it is working fine.
 
Share this answer
 
Comments
Dew Drops 7-Apr-14 0:26am    
I Dont understand about the " Product product = Product.GetProduct(Convert.ToInt32(productID));" line. what is Product and product here?
Member 12868822 13-Jun-17 6:57am    
what is Product product = Product.GetProduct(Convert.ToInt32(productID));
what is GetProduct in this line. it is giving error when we execute it.
navyjax2 2-Sep-21 16:45pm    
"Product.GetProduct()" calls a function in the Product controller called "GetProduct()" that you would need to build that returns a model of the Product table to "product" from the database, given a productID that is passed in.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900