简体   繁体   English

如何在MVC 4中扩展关于模型属性更改的Razor视图

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

I'm using EF and MVC 4 to develop web store application 我正在使用EF和MVC 4开发Web商店应用程序

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. 在此域模型中,ProductProperty的列表取决于ProductCategoryId,因为每个ProductProperty都分配给ProductCategories之一。

Therefore in a Create View when ProductCategoryId DropDownList changed several other DropDownLists should appear for each of ProductProperty reffered to selected ProductCategoryId. 因此,在创建视图中,当ProductCategoryId DropDownList更改时,应将其他多个DropDownLists出现在每个ProductProperty的基础上,以替代所选ProductCategoryId。 To implement this I'm submitting the form on DropDownList change using this code in a Razor view: 为了实现这一点,我将在Razor视图中使用以下代码提交DropDownList更改上的表单:

@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? 是否有更好的方法来处理在View中为与选定ProductCategory相关的每个ProductProperty添加DropDownLists的问题?

And how to determine whether form was submitted by save button or dropdownlist change? 以及如何确定表单是通过保存按钮还是通过下拉列表更改提交的?

It is possible with jQuery Ajax. jQuery Ajax是可能的。 See below! 见下文!

In order to populate the items in dropdown lists, you can use DropDownList or DropDownListFor controls in your view. 为了填充下拉列表中的项目,可以在视图中使用DropDownList或DropDownListFor控件。

If you're using @.Html.DropDownList you can write code as below in, 如果您使用的是@.Html.DropDownList ,则可以按以下方式编写代码,

Controller:DropDownList 控制器: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, 如果您使用@.Html.DropDownListFor您可以按以下方式编写代码,

Controller:DropDownListFor 控制器: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: 要以JSON形式获取结果以通过jQuery进行绑定,可以使用如下所示的Create方法:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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