Home > Mobile >  How to send View Model only from Main Model in asp.net mvc?
How to send View Model only from Main Model in asp.net mvc?

Time:09-18

I have using HTML.BeginForm for my MVC Form.Here is the html code


@model TodayViewModel
@{
    ViewBag.Title = "Work Completed Today";
    Layout = "~/Views/Shared/_LayoutBackend.cshtml";
}

 @using (Html.BeginForm("Create", "CustomActivity", FormMethod.Post, new { role = "form", @id = "customActivityForm", @class = "activityForm" }))
                    {
                        <div>
                            <div class="myClass">
                            </div>

                            <div class="container" id="workordercategories">
                                @Html.LabelFor(m => m.CustomActivity.WorkOrderCategoriesName, new { @class = "" })
                                @Html.TextBoxFor(m => m.CustomActivity.WorkOrderCategoriesName, new { @class = "w100p mb0" })
                                @Html.ValidationMessageFor(m => m.CustomActivity.WorkOrderCategoriesName, "", new { @class = "text-danger" })
                            </div>


                            <div class="container" id="activity">
                                @Html.LabelFor(m => m.CustomActivity.Activity, new { @class = "" })
                                @Html.TextBoxFor(m => m.CustomActivity.Activity, new { @class = "w100p mb0" })
                                @Html.ValidationMessageFor(m => m.CustomActivity.Activity, "", new { @class = "text-danger" })
                            </div>
                        </div>
                     }

and my view model is

  public class TodayViewModel
    {
        public IList<TodayListViewModel> TodaysVM { get; set; }
        public CustomActivityViewModel CustomActivity { get; set; }

    }

 public class CustomActivityViewModel
    {
        [Required, Display(Name = "Work Category Name")]
        public string WorkOrderCategoriesName { get; set; }
        [Required]
        public string Activity { get; set; }
    }

while submitting form the Controller Method is:

[HttpPost]
        public ActionResult Create(TodayViewModel model)
        {
            // to do here
        }

In Controller Method I have to use TodayViewModel in which there are two method one of them (TodaysVM) is always null. Is there any way to submit form so that I can use CustomActivityViewModel instead of TodayViewModel in Controller?? Right Now If I use CustomActivityViewModel the value in the controller is null.

CodePudding user response:

If you can't use CustomActivityViewModel in the View try

[HttpPost]
public ActionResult Create(TodayViewModel model)
{
     CustomActivityViewModel obj = model.CustomActivity;

     //....
}
  • Related