简体   繁体   English

如何将相同的视图模型用于不同的视图(排除必需的属性)?

[英]How do I use same view model but for different view excluding the required properties?

I have a view model for a view AddAppointment. 我有一个视图模型,用于视图AddAppointment。 It has many properties of which 2 are Required (I wrote Required attribute over it). 它具有许多特性,其中2 需要 (我写了必需的特性在它)。

Now I want to use the same model for another view but excluding the properties which are required but it doesn't work ie it's invalid. 现在,我想对另一个视图使用相同的模型,但不包括必需的属性,但它不起作用,即无效。

What to do apart from writing another view model? 除了编写另一个视图模型外,还要做什么?

View Model: 查看模型:

  public class AddBookingsViewModel
    {


        public string CustomerName { get; set; }


        public string ContactNo { get; set; }
        public string VehicleRegNo { get; set; }
        public short fk_VehicleMakeID { get; set; }
        public string VehicleModel { get; set; }

        [Required(ErrorMessage = "Select appointment time ")]
        public int fk_TimeSlotID { get; set; }

        public byte fk_BookingModeID { get; set; }
        public int EntryUserID { get; set; }
        public int ReturnBookingID { get; set; }    

        [Required(ErrorMessage="Fill in the appointment date")]
        [DataType(DataType.Date)]
        public DateTime? AppointmentDate { get; set; }

    }

View: (Where it is used) 查看:(使用它的地方)

@model ZahidCarWash.ViewModels.AddBookingsViewModel

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



<!--  page banner -->

<!--  end page banner  -->
@using (Html.BeginForm())
{
    <!--  appointments -->
    <div id="appointments" class="appointment-main-block appointment-two-main-block">
        <div class="container">
            <div class="row">
                <div class="section text-center">
                    <h3 class="section-heading text-center">Get an Appointment</h3>
                </div>

                <div class="col-md-8 col-sm-12">
                    <div class="appointment-block">

                        <h5 class="form-heading-title"><span class="form-heading-no">1.</span>Vehicle Information</h5>
                        <div class="row">
                            <div class="col-sm-4">
                                <div class="dropdown">

                                    @Html.DropDownListFor(Model => Model.fk_VehicleMakeID, new SelectList(ZahidCarWash.DAL.VehicleMakesRepository.getVehicleMakes(), "VehicleMakeID", "MakeTitle"),
          new { @class = "form-control" })

                                </div>
                            </div>
                            <div class="col-sm-4">
                                @Html.EditorFor(Model => Model.VehicleModel, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter Vehicle Model" } })
                            </div>
                            <div class="col-sm-4">
                                @Html.EditorFor(Model => Model.VehicleRegNo, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter Vehicle Reg No." } })
                            </div>
                        </div>

                        <h5 class="form-heading-title"><span class="form-heading-no">2.</span>Contact Details</h5>
                        <div class="row">
                            <div class="col-sm-4">
                                @Html.EditorFor(Model => Model.CustomerName, new { htmlAttributes = new { @class = "form-control", placeholder = "Customer Name" } })
                                @Html.ValidationMessageFor(Model => Model.CustomerName, "", new { @class = "ErrorMessages" })
                            </div>
                            <div class="col-sm-4">
                                @Html.EditorFor(Model => Model.ContactNo, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter Contact Number." } })
                                @Html.ValidationMessageFor(Model => Model.ContactNo, "", new { @class = "ErrorMessages" })
                            </div>
                        </div>
                        <button type="submit" class="btn btn-default pull-right">Book Now</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
}

Controller: 控制器:

  public JsonResult AddManualAppointment(AddBookingsViewModel AddBookingVM)
    {
        if (ModelState.IsValid)
        {
            AddBookingVM.fk_BookingModeID = 2;
            int ReturnRowsCount = BookingRep.InsertCustomerAppointments(AddBookingVM, out ReturnStatus, out ReturnMessage, out ReturnBookingID);

        }
        else
        {

        }

        return Json(new { ReturnMessageJSON = ReturnMessage, ReturnStatusJSON = ReturnStatus });
    }

Data is passed through ajax: 数据通过ajax传递:

  <script type="text/javascript">



        //to add an appointment

        $('form').submit(function (e) {
            e.preventDefault();
            if (!$(this).valid()) {
                return;
            }

            var url = '@Url.Action("AddManualAppointment")';
            var data = $(this).serialize();

            $.post(url, data, function (response) {

                if (response.ReturnStatusJSON == true) {

                    swal("Booked !", response.ReturnMessageJSON, "success");


                    $("#VehicleRegNo").val("");
                    $("#VehicleModel").val("");

                    $("#CustomerName").val("");
                    $("#ContactNo").val("");


                }
                else {
                    swal("Sorry !", response.ReturnMessageJSON, "error");
                }
            });

        });

    </script>
    <!--End Custom Scripts-->
}

我猜快速和肮脏的方法是使用@ Html.Hiddenfor并从控制器内部使用新的datetime填充值

You can split your view model into a version with and without the required attributes using inheritance: 您可以使用继承将视图模型分为具有和不具有必需属性的版本:

public class AddBookingsViewModel
{
    public string CustomerName { get; set; }
    public string ContactNo { get; set; }
    public string VehicleRegNo { get; set; }
    public short fk_VehicleMakeID { get; set; }
    public string VehicleModel { get; set; }
    public byte fk_BookingModeID { get; set; }
    public int EntryUserID { get; set; }
    public int ReturnBookingID { get; set; }    
}

public class AddBookingsViewModelWithAppointment : AddBookingsViewModel
{
    [Required(ErrorMessage = "Select appointment time ")]
    public int fk_TimeSlotID { get; set; }
    [Required(ErrorMessage="Fill in the appointment date")]
    [DataType(DataType.Date)]
    public DateTime? AppointmentDate { get; set; }
}

This allows you to use the appropriate view model in your situation and still maintain compatibilty through polymorphism. 这使您可以根据情况使用适当的视图模型,并通过多态性保持兼容性。

If you need the optional properties in your base class, you can make your properties virtual and apply the attribute in the derived class: 如果您需要基类中的可选属性,则可以将属性虚拟化并在派生类中应用该属性:

public class AddBookingsViewModel
{
    public string CustomerName { get; set; }
    public string ContactNo { get; set; }
    public string VehicleRegNo { get; set; }
    public short fk_VehicleMakeID { get; set; }
    public string VehicleModel { get; set; }
    public byte fk_BookingModeID { get; set; }
    public int EntryUserID { get; set; }
    public int ReturnBookingID { get; set; }    
    public virtual int fk_TimeSlotID { get; set; }
    public virtual DateTime? AppointmentDate { get; set; }
}

public class AddBookingsViewModelWithAppointment : AddBookingsViewModel
{
    [Required(ErrorMessage = "Select appointment time ")]
    public override int fk_TimeSlotID {
        get => base.fk_TimeSlotID;
        set => base.fk_TimeSlotID = value;
    }
    [Required(ErrorMessage="Fill in the appointment date")]
    [DataType(DataType.Date)]
    public override DateTime? AppointmentDate {
        get => base.AppointmentDate;
        set => base.AppointmentDate = value;
    }
}

Use the veriant that works best in your business case. 使用最适合您的业务案例的版本。

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

相关问题 如何获取视图中视图模型的属性? - How do I get to the properties of the view model in the view? 如何在 mvc4 中的同一视图中访问不同的模型属性? 有可能吗? - How to access different model properties in same view in mvc4?Is it possible? 如何在mvc4的同一视图中使用不同的模型? - How to use different model in same view in mvc4? 如何将模型属性传递给具有其他模型的局部视图? - How do I pass a model property to a partial view with a different model? 如何在不同的视图中引用相同的视图模型 - How to reference same view model in different views 如果另一个局部视图使用其他模型,如何传递具有特定模型的局部视图? - How do I pass a partial view with a specific model if another partial view is using a different model? 如何在同一视图中的 3 个不同视图模型下使用 3 个不同的数据表? - How to use 3 different datatables under 3 different view models in same view? 当父视图具有相同模型时,如何将局部视图中的 HTML 表单数据序列化? - How do I get HTML form data in Partial View to be serialized when parent view has same model? 如何在将视图模型传递给具有不同路由的视图时使用RedirectToAction - How to use RedirectToAction while passing view model to a view with different route 如何在一个视图中使用两个不同的模型? - How do I use two different models in one view?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM