13

that's my function:

 <script> function Calculate()
     {
         var ItemPrice = document.getElementById("price");
         var weight = document.getElementById("weight");
         var SelWeight = weight.options[weight.selectedIndex].value;
         alert(SelWeight);
         var Category = document.getElementById("SelectedCategory");
         var SelCategory = Category.options[Category.selectedIndex].value;
         alert(SelCategory);

     }
    </script>

i want to get SelCategories.Tax and SelCategories.Duty to add them to weight value and total price to show the total in a label.. I'm using ASP.NET MVC 4 and this is my Model that i want to use

public class CategoriesModel
    {
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
        public decimal Duty { get; set; }
        public decimal Tax { get; set; }
        public IEnumerable<SelectListItem> CategoriesList { get; set; }
    }
YaraHanaa
  • 309
  • 1
  • 3
  • 13
  • You should have a `controller` and an `action method` which will serve the data that you want in the client. And you may make an ajax call to retrieve the data from the controller action. – Shuhel Ahmed Dec 09 '13 at 13:19
  • the problem is the other dropdown list is a ` – YaraHanaa Dec 09 '13 at 13:29
  • http://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown – Matt Bodily Dec 09 '13 at 14:40
  • i have 2 dropdown list 1- is using ` – YaraHanaa Dec 09 '13 at 15:16
  • the link I posted shows how you can get the selected item of any dropdown no matter how it is built selecting on the id or the class of the dropdown. Is there something about yours that wouldn't work? – Matt Bodily Dec 09 '13 at 15:23
  • @MattBodily the thing is that i got the id from both lists but i want to get more from the model (or database) by this id to use it in javascript code – YaraHanaa Dec 09 '13 at 15:28
  • for that use an ajax call. pass the selected id back to the controller and return whatever data you need that goes with the id. see my answer here http://stackoverflow.com/questions/19359204/asp-net-mvc-4-passing-object-variable-through-actionlink/19360998#19360998 – Matt Bodily Dec 09 '13 at 15:32
  • You have a complete sample of what you want to achieve in my answer. – JotaBe Dec 09 '13 at 16:25
  • Complete details of this is explained here http://stackoverflow.com/a/41312348/2592042 – Rajshekar Reddy Dec 24 '16 at 11:49

4 Answers4

31

I think the best approach here is to use Json and something like Vue.js, Knockout.js, etc. (but also you can do it without these libraries, if your case is simple).

First, you need to install Json support with a command in PM console:

PM> install-package NewtonSoft.Json

Then, in your view you can convert your model to javascript object like this:

@model ...
@using Newtonsoft.Json

...

<script type="text/javascript">

    var data = @Html.Raw(JsonConvert.SerializeObject(this.Model));

</script>

Then you can access all the properties in your model with in plain JavaScript:

var id = data.CategoryID;

That's it! Use knockout (update 2018: this is obsolete, there is no reason you should use knockout now) if your logic is complicated and you want to make your view more powerful. It could be a little bit confusing for newbie, but when you get it, you'll gain the super-powerful knowledge and will be able to simplify your view code significantly.

Roman Pushkin
  • 5,639
  • 3
  • 40
  • 58
  • i installed it and i wrote this var data = `@Html.Raw(JsonConvert.SerializeObject(this.Model));` but i can't find Category in data :/ – YaraHanaa Dec 10 '13 at 08:19
  • @YaraHanaa, you don't have "Category" property in your model. What is "Category"? – Roman Pushkin Dec 10 '13 at 09:03
  • i mean "CategoryId"... do u know how to post an image here to show u what i mean?? – YaraHanaa Dec 10 '13 at 09:13
  • 1
    First, make sure your @{ var data = ... } block is inside of script tag. Second, you won't be able to access these properties via IntelliSense. Visual Studio is not so clever at the moment, and just can't determine real properties. Put alert(data.CategoryID); right after the @{ ... } block and open the page in your browser. But, again, make sure this block is inside of script tag! – Roman Pushkin Dec 10 '13 at 09:53
2

You need to create actions (methods in the controller) that return JsonResult.

From the client side, make ajax calls to the server to recover and use that data. The easiest way to do this is to use any of the jQuery ajax methods.

   public JsonResult GetData(int id)
    {
        // This returned data is a sample. You should get it using some logic
        // This can be an object or an anonymous object like this:
        var returnedData = new
        {
            id,
            age = 23,
            name = "John Smith"
        };
        return Json(returnedData, JsonRequestBehavior.AllowGet);
    }

When you use a jQuery get to the /ControllerName/GetData/id, you'll get a JavaScript object in the success callback that can be used in the browser. This JavaScript object will have exactly the same properties that you defined in the server side.

For example:

function getAjaxData(id) {
    var data = { id: id };
    $.get('/Extras/GetData/1', // url
        data, // parameters for action
        function (response) { // success callback
            // response has the same properties as the server returnedObject
            alert(JSON.stringify(response)); 
        },
        'json' // dataType
    );
}

Of course, in the success callback, instead of making an alert, just use the response object, for example

if (response.age < 18) { ... };

Note that the age property defined in the server can be used in the JavaScript response.

halfer
  • 19,824
  • 17
  • 99
  • 186
JotaBe
  • 38,030
  • 8
  • 98
  • 117
1

If you prefer a class try jsmodel. After converting the mvc view model to javascript it adds the benefit of retrieving DOM updates.

var jsmodel = new JSModel(@Html.Raw(Json.Encode(Model)));

Then anytime you want to get the latest state of the DOM do this to update your variable:

var model = jsmodel.refresh();

Website: http://chadkuehn.com/jquery-viewmodel-object-with-current-values/

There is also a nuget: https://www.nuget.org/packages/jsmodel/

2Yootz
  • 3,971
  • 1
  • 36
  • 31
  • Besides, don't forget to add the "bundles" of jsmodel. In the jQuery, then you can use $(jsmodel.SomeProperty) directly. – Yang C Apr 03 '15 at 09:31
0
var errors = '@Html.Raw(Json.Encode(ViewData.ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)))';
var errorMessage=JSON.parse(errors);
Mohamed.Abdo
  • 2,054
  • 1
  • 19
  • 12