简体   繁体   中英

How to extend Razor View on model property change in MVC 4

I'm using EF and MVC 4 to develop web store application

I have a Product domain model:

    public class Product
     {        
            public int Id{ get; set;}

            public decimal InitialPrice { get;set;}

            public string Name {get;set;}    

            public byte ProductCategoryId { get;set; }

            public ProductCategory ProductCategory{get;set;}

            public List<ProductProperty>  ProductProperties 
            {get{return ProductCategory.ProductProperties }}
     }

In this domain model List of ProductProperty depends on ProductCategoryId because every ProductProperty assigned to one of ProductCategories.

Therefore in a Create View when ProductCategoryId DropDownList changed several other DropDownLists should appear for each of ProductProperty reffered to selected ProductCategoryId. To implement this I'm submitting the form on DropDownList change using this code in a Razor view:

@Html.DropDownListFor(model => model.ProductCategoryId, (SelectList)ViewBag.ProductCategoriesSelectList, "Select", new { onchange = "submit()"})

Now in my Controller View I need to know whether the form was submitted by save button or dropdown change event, to skip validation and save operations.

The questions are:

Is there a better way to deal with adding DropDownLists in a View for each of ProductProperties reffered to selected ProductCategory?

And how to determine whether form was submitted by save button or dropdownlist change?

It is possible with jQuery Ajax. See below!

In order to populate the items in dropdown lists, you can use DropDownList or DropDownListFor controls in your view.

If you're using @.Html.DropDownList you can write code as below in,

Controller:DropDownList

public ActionResult Index(int id)
{
    ViewBag.ProductCategoryID = new SelectList(db.GetProductCategories.ToList(), "ProductCategoryID", "ProductCategoryName", "Select");
    return View();
}

View:

@Html.DropDownList("ProductCategoryID",null,
                   new {@onchange="submitform('dropdown')"})

If your using @.Html.DropDownListFor you can write code as below in,

Controller:DropDownListFor

public ActionResult Index(int id)
{
    ViewBag.ProductCategoryID = db.GetProductCategories.ToList();
    return View();
}

View:

@Html.DropDownListFor(model => model.ProductCategoryID, (SelectList)ViewBag.ProductCategoryID, "Select", new { onchange = "submitform('dropdown')"})

--

 <script type="text/javascript">
    $(document).ready(function () {
        var ProductCatID = $("#ProductCategoryID").val();
        submitform = function (flag) {
            var param = { ProdCatID: ProductCatID, Flag: flag };
            var ul = '@Url.Action("Create", "YourControllerName")';
             $.ajax({
                 url: ul + "?ProdCatID=" + ProductCatID + "&&Flag=" + flag,
                 type: 'GET',
                 datatype: "json",
                 contentType: "application/json; charset=utf-8",
                 async: true,
                 data: JSON.stringify(param),
                 success: function (response) {
                     if (response != "") {                               
                         alert("Record Added Successfully!");
                     }                        
                 },
                 error: function (xhr, status, error) {
                     alert("R:" + xhr.responseText + " S:" + status + " E:" + error);
                 }
             });
        }
    });
</script>

Controller:

public ActionResult Create(string ProdCatID, string flag)
{
    if (ModelState.IsValid)
    {
        if (flag == "dropdown")
        {
            //your code goes here.
        }
        if (flag == "button")
        {
            //your code goes here/
        }
    }
}

To get the Result as JSON to bind through jQuery you can use Create method like below:

public JsonResult Create(string ProdCatID, string Flag)
{
    if (ModelState.IsValid)
    {
        if (flag == "dropdown")
        {
            //your code goes here.
        }
        if (flag == "button")
        {
            //your code goes here/
        }
    }
    var model = db.GetProductCategories.where(id=>id.ProductCategoryID==ProductCatID).ToList();

    return Json(model, JsonRequestBehavior.AllowGet);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM