0

In my ASP.net MVC App (using Razor views) I have a "ProductDetails" view.
This retrieves a "Product" model from the database.

The Product object, has a collection of "ProductVariation" (size, price, inStock etc...)

Something like this:

public class Product()
{
  public int ID { get; set; }
  public str Name { get; set; }

  public ICollection<ProductVariation> Variations { get; set; }
}

public class ProductVariation
{
  public int VariationID {get;set;}
  public bool ProductID {get;set;}
  public bool InStock {get;set;}
  public double Price {get;set;}
}

(Obviously this is a very cut down model)

On my ProductDetails view, I have a dropdown to be able to select a variation.

What I want to be able to do is show / hide elements based on the selection.

Currently, I've got the price updating etc.. using jQuery. I do this by creating a series of tags with an id such as "1234-price" (1234 representing the VariationID)

The value of my select element is the VariationID So, i basically use a jQuery selector to get the value of the ID i want to show, and hide all the others. This is working fine.

However, if a product is not available (ie InStock is false) I want to hide the "buy" button, and display some out of stock text.

How can I go about doing something like this?

Should I create an array of Javascript "product" objects on the page, from the model returned by my controller?

Is there a better way?

1 Answer 1

2

Based on what you're describing, using a templating system, such as this: http://api.jquery.com/category/plugins/templates/

First, you would make a javascript object that reflects your database model. For example.... (ideally, this would be automatically generated with something like:

<script>
  var viewModel = @Html.Raw(JsonNetConverter.Serialize(Model))
</script>

However you go about generating that, you should end up with something like this:

var viewModel = { VariationID: 1, ProductID: 1, InStock: true, Price: 9.99 };

In your dropdown menu where users can select product variations, you would do something like this:

<select name="ProductVariations">
    <option value="1">Variation 1</option>
    <option value="2">Variation 2</option>
</select>

You would then need to make an action in your controller, like:

[HttpPost]
public ActionResult GetVariationById(int id)
{
    var model = new VariationModel();
    var variation = model.getVariationById(id);
    return View(variation);
}

Finally, you re-render your template with the new data you got back from your model:

$("#view-template").tmpl(viewModel).appendTo("#selector");
Sign up to request clarification or add additional context in comments.

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.