locked
Task Controller - Calling from View RRS feed

  • Question

  • User1352447851 posted

    I am trying to use a button in a View to execute the below and update the status shown on the page:

    public async Task<IActionResult> Create(int? id)

            {

                var test = await _context.Test.FindAsync(id);

                if (id != test.Id)

                {

                    return NotFound();

                }

                if (ModelState.IsValid)

                {

                    return NotFound();

                }

                MyMethod myMethod = new MyMethod();

                string name = test.Firstname + " " + test.Lastname;

                myMethod.Create(name);

                test.Status = "Completed";

                _context.Update(test);

                await _context.SaveChangesAsync();

                return View();

            }

    I understand controllers when just inputing a string and typing the route in the browser bar, but I have no idea how to call the above. Should it be a controller or just a method in the page model? 

    For example (from a 'List' page model):

                <td>

                    @Html.DisplayFor(modelItem => item.Status)

                </td>

    <a class="btn" asp-action="Create" asp-controller="Test" method="post">Create</a>

    I am just finding the documentation a bit abstract with no complete examples showing full code. 

    Is it best practice to place my Task in a Controller or Page model, and how do I fix the above to correctly call the Task?

    Monday, February 11, 2019 8:31 AM

Answers

  • User-1038772411 posted

    Simple example to demonstrate how to use it in core

    basic form 

    @model WebApplication2.Models.HomeModel
    	@{
    		ViewData["Title"] = "Home Page";
    	}
    	<br />
    	<form asp-action="" method="post">
    		<div class="row">
    			<div class="col-md-12">
    				<div class="md-form">
    					<label class="control-label" for="Name">Name</label>
    					<input asp-for="Name" class="form-control" type="text" id="Name" name="Name" />
    					<span asp-validation-for="Name" class="text-danger"></span>
    				</div>
    			</div>
    		</div><br />
    		<div class="row">
    			<div class="col-md-12">
    				<div class="md-form">
    					<input type="submit" value="Calculate" class="btn btn-default" formaction="Home/Index" />
    				</div>
    			</div>
    		</div>
    
    	</form>

    Model 

    public class HomeModel
        {
            [Required]
            public string Name { get; set; }
        }

    Controller

    public class HomeController : Controller
        {
            [HttpGet]
            public IActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            public IActionResult Index(HomeModel model)
            {
                if (ModelState.IsValid)
                {
    
                    return View(model);
                }
               
                return View(model);
            }
    	}

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 13, 2019 5:31 AM

All replies

  • User-1038772411 posted

    Try This 

    public async Task<IActionResult> Create(int? id)
    
            {
    
                var test = await _context.Test.FindAsync(id);
    
                if (id != test.Id)
    
                {
    
                    return NotFound();
    
                }
    
                if (ModelState.IsValid)
    
                {
    
                    return NotFound();
    
                }
    
                MyMethod myMethod = new MyMethod();
    
                string name = test.Firstname + " " + test.Lastname;
    
                myMethod.Create(name);
    
                test.Status = "Completed";
    
                _context.Update(test);
    
                await _context.SaveChangesAsync();
    
                return View(test); //Just Pass your model in view and show in view page
    
            }

    Monday, February 11, 2019 9:47 AM
  • User1352447851 posted

    Sorry if my question wasn't clear.

    I don't know whether to put my Task in a Controller or PageModel object - and I don't know how to call it. My Create method doesn't ever run because I don't know how to code the button in the cshtml.

    <a class="btn" asp-action="Create" asp-controller="Test" method="post">Create</a>

    Monday, February 11, 2019 10:51 AM
  • User1120430333 posted

    I don't know whether to put my Task in a Controller or PageModel object -

    IMO, the code should be put into a  class/object in the Models folder and the controller should call a method  in the object.

    It follows the MVC and SoC principles of not making calls to the database from the controller.

    https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/ 

    IMO, it's just basic MVC principles where an object in the Models folder has the responsibility and not the controller.

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models-views-and-controllers-cs

    <copied>

    An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.

    A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.
    In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.

    <end>

    and I don't know how to call it. My Create method doesn't ever run because I don't know how to code the button in the cshtml.

    I'll give you a basic code example.

    @using ProgMgmntCore2UserIdentity.Models
    @model ProjectViewModels.Project
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <title>Create</title>
    </head>
    <style type = "text/css"> 
        .editor-field > label
        {
            float: left;
            width: 150px;
        }
        .txtbox {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 12px;
            background: white;
            color: black;
            cursor: text;
            border-bottom: 1px solid #104A7B;
            border-right: 1px solid #104A7B;
            border-left: 1px solid #104A7B;
            border-top: 1px solid #104A7B;
            padding-top: 10px;
        }       
    </style> 
    
    <body>
    <h1>Project</h1>
    
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(false, "", new { @class = "text-danger" })
    
    <fieldset>
    
        <legend>Create</legend>
    
        <div class="editor-field">
            @Html.Label("Project Name:")
            @Html.TextBoxFor(model => model.ProjectName, new { @Cssclass = "txtbox" })
            @Html.ValidationMessageFor(model => model.ProjectName)
        </div>
        <br />
        <div class="editor-field">
            @Html.Label("Client Name:")
            @Html.TextBoxFor(model => model.ClientName, new { @Cssclass = "txtbox" })
            @Html.ValidationMessageFor(model => model.ClientName)
        </div>
        <br />
        <div class="editor-field">
            @Html.Label("Technology:")
            @Html.TextBoxFor(model => model.Technology, new { @Cssclass = "txtbox" })
            @Html.ValidationMessageFor(model => model.Technology)
        </div>
        <br />
        <div class="editor-field">
            @Html.Label("Start Date:")
            @Html.TextBoxFor(model => model.StartDate, new { @Cssclass = "txtbox" })
            @Html.ValidationMessageFor(model => model.StartDate)
        </div>
        <br />
        <div class="editor-field">
            @Html.Label("End Date:")
            @Html.TextBoxFor(model => model.EndDate, new { @Cssclass = "txtbox" })
            @Html.ValidationMessageFor(model => model.EndDate)
        </div>
        <br />
        <div class="editor-field">
            @Html.Label("Cost:")
            @Html.TextBoxFor(model => model.Cost, new { @Cssclass = "txtbox" })
            @Html.ValidationMessageFor(model => model.Cost)
        </div>
        <br />
        <div class="editor-field">
            @Html.Label("Project Type:")
            @Html.DropDownList("ddlProjectTypes", Model.ProjectTypes, "Select....")
        </div>
        <br />
        <p>
            <input type="submit" name="submit" value="Save" />
            <input type="submit" name="submit" value="Cancel" />
        </p>
    
    </fieldset>
    }
    
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc.Rendering;
    
    namespace ProgMgmntCore2UserIdentity.Models
    {
        public class ProjectViewModels
        {
            public class Project
            {
                public int ProjectId { get; set; }
    
                [Required(ErrorMessage = "Client Name is required")]
                [StringLength(50)]
                public string ClientName { get; set; }
    
                [Required(ErrorMessage = "Project Name is required")]
                [StringLength(50)]
                public string ProjectName { get; set; }
    
                [Required(ErrorMessage = "Technology is required")]
                [StringLength(50)]
                public string Technology { get; set; }
    
                [Required(ErrorMessage = "Project Type is required")]
                public string ProjectType { get; set; }
    
                [Required(ErrorMessage = "Start Date is required")]
                [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy}")]
                public DateTime? StartDate { get; set; }
    
                [Required(ErrorMessage = "End Date is required")]
                [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy}")]
                public DateTime? EndDate { get; set; }
    
                [Required(ErrorMessage = "Cost is required")]
                public decimal? Cost { get; set; }
    
                public List<SelectListItem> ProjectTypes { get; set; }
            }
           
            public List<Project> Projects { get; set; }
            
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Entities;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.Extensions.Caching.Memory;
    using ProgMgmntCore2UserIdentity.WebApi;
    
    namespace ProgMgmntCore2UserIdentity.Models
    {
        public class ProjectModel : IProjectModel
        {
            private readonly IMemoryCache _memoryCache;
            private readonly IWebApi _webApi;
    
            public ProjectModel(IWebApi webApi, IMemoryCache memoryCache)
            {
                _memoryCache = memoryCache;
                _webApi = webApi;
            }
    
            public ProjectViewModels GetProjectsByUserId(string userid)
            {
                var vm = new ProjectViewModels {Projects = new List<ProjectViewModels.Project>()};
    
                var dtos = _webApi.GetProjsByUserIdApi(userid).ToList();
                
                vm.Projects.AddRange(dtos.Select(dto => new ProjectViewModels.Project()
                {
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                }).ToList());
    
                return vm;
            }
    
            public ProjectViewModels.Project GetProjectById(int id)
            {
                var responseDto = _webApi.GetProjByIdApi(id);
    
                var project = new ProjectViewModels.Project
                {
                    ProjectId = responseDto.ProjectId,
                    ClientName = responseDto.ClientName,
                    ProjectName = responseDto.ProjectName,
                    Technology = responseDto.Technology,
                    ProjectType = responseDto.ProjectType,
                    StartDate = responseDto.StartDate,
                    EndDate = responseDto.EndDate,
                    Cost = responseDto.Cost
                };
    
                return project;
            }
    
            public ProjectViewModels.Project Create()
            {
                var project = new ProjectViewModels.Project();
                return PopulateSelectedList(project);
            }
    
            public void Create(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,  
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                _webApi.CreateProjectApi(dto);
            }
    
            public ProjectViewModels.Project Edit(int id)
            {
                var responseDto = _webApi.GetProjByIdApi(id);
    
                var project = new ProjectViewModels.Project
                {
                    ProjectId = responseDto.ProjectId,
                    ClientName = responseDto.ClientName,
                    ProjectName = responseDto.ProjectName,
                    Technology = responseDto.Technology,
                    ProjectType = responseDto.ProjectType,
                    StartDate = responseDto.StartDate,
                    EndDate = responseDto.EndDate,
                    Cost = responseDto.Cost
                };
    
                project = PopulateSelectedList(project);
    
                return project;
            }
    
            public void Edit(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                _webApi.UpdateProjectApi(dto); 
            }
    
            public void Delete(int id)
            {
                _webApi.DeleteProjectApi(new DtoId{Id = id});
            }
    
            public ProjectViewModels.Project PopulateSelectedList(ProjectViewModels.Project project)
            {
                bool isExist = _memoryCache.TryGetValue("DtoCache", out DtoCache dtocache);
    
                if (!isExist)
                {
                    dtocache = _webApi.GetCacheApi();
              
                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                        .SetSlidingExpiration(TimeSpan.FromSeconds(30));
                    
                    _memoryCache.Set("DtoCache", dtocache, cacheEntryOptions);
                }
    
                project.ProjectTypes = new List<SelectListItem>();
    
                foreach (var pt in dtocache.ProjectTypes)
                {
                    var sli = new SelectListItem {Value = pt.Value, Text = pt.Text};
                    project.ProjectTypes.Add(sli);
                }
           
                var selected = (from a in project.ProjectTypes.Where(a => a.Value == project.ProjectType) select a)
                    .SingleOrDefault();
    
                if (selected != null)
                    selected.Selected = true;
    
                return project;
            }
        }
    }
    
    using System;
    using System.Linq;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.ModelBinding;
    using ProgMgmntCore2UserIdentity.Models;
    
    namespace ProgMgmntCore2UserIdentity.Controllers
    {
        public class ProjectController : Controller
        {
            private readonly IProjectModel _projectModel;
            private readonly IModelHelper _modelHelper;
           
            public ProjectController(IProjectModel projectModel,   IModelHelper modelHelper)
            {
                _projectModel = projectModel;
                _modelHelper = modelHelper;
            }
    
            // GET: Project
            [Authorize]
            public ActionResult Index()
            {
                return View(_projectModel.GetProjectsByUserId(User.Identity.Name));
            }
    
            [Authorize]
            public ActionResult Details(int id = 0)
            {
                return id == 0 ? null : View(_projectModel.Edit(id));
            }
    
            [Authorize]
            public ActionResult Create()
            {
                return View(_projectModel.Create());
            }
    
            [Authorize]
            [HttpPost]
            public ActionResult Create(ProjectViewModels.Project project, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
    
                ValidateddlProjectTypes();
    
                project.ProjectType = (Request.Form["ddlProjectTypes"]);
    
                if (ModelState.IsValid && _modelHelper.IsEndDateLessThanStartDate(project, "Project"))
                    ModelState.AddModelError(string.Empty, "End Date cannot be less than Start Date.");
    
                if (!ModelState.IsValid) return View(_projectModel.PopulateSelectedList(project));
    
                _projectModel.Create(project, User.Identity.Name);
                return RedirectToAction("Index");
            }
    
            [Authorize]
            public ActionResult Edit(int id = 0)
            {
                return id == 0 ? null : View(_projectModel.Edit(id));
            }
    
            [Authorize]
            [HttpPost]
            public ActionResult Edit(ProjectViewModels.Project project, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
    
                if (ModelState.IsValid && _modelHelper.IsEndDateLessThanStartDate(project, "Project"))
                    ModelState.AddModelError(String.Empty, "End Date cannot be less than Start Date.");
    
                if (!ModelState.IsValid) return View(_projectModel.PopulateSelectedList(project));
    
                var theproject = new ProjectViewModels.Project();
    
                theproject = project;
    
                theproject.ProjectType = Request.Form["ProjectType"];
    
                _projectModel.Edit(theproject, User.Identity.Name);
                return RedirectToAction("Index");
            }
    
            public ActionResult Delete(int id = 0)
            {
                if (id > 0) _projectModel.Delete(id);
    
                return RedirectToAction("Index");
            }
       
            public ActionResult Cancel()
            {
                return RedirectToAction("Index", "Home");
            }
    
            public ActionResult UploadFile(int id)
            {
                return RedirectToAction("Index", "Upload", new { id = id, type = "PM" });
            }
    
            private void ValidateddlProjectTypes()
            {
                if (Request.Form["ddlProjectTypes"] == string.Empty)
                  return;
           
                foreach (var key in ModelState.Keys.ToList().Where(key => ModelState.ContainsKey(key)))
                {
                    if (key != "ProjectType") continue;
                    ModelState[key].Errors.Clear();
                    ModelState[key].ValidationState = ModelValidationState.Valid;
                }
            }
        }
    }

    Monday, February 11, 2019 11:55 AM
  • User-1038772411 posted

    Simple example to demonstrate how to use it in core

    basic form 

    @model WebApplication2.Models.HomeModel
    	@{
    		ViewData["Title"] = "Home Page";
    	}
    	<br />
    	<form asp-action="" method="post">
    		<div class="row">
    			<div class="col-md-12">
    				<div class="md-form">
    					<label class="control-label" for="Name">Name</label>
    					<input asp-for="Name" class="form-control" type="text" id="Name" name="Name" />
    					<span asp-validation-for="Name" class="text-danger"></span>
    				</div>
    			</div>
    		</div><br />
    		<div class="row">
    			<div class="col-md-12">
    				<div class="md-form">
    					<input type="submit" value="Calculate" class="btn btn-default" formaction="Home/Index" />
    				</div>
    			</div>
    		</div>
    
    	</form>

    Model 

    public class HomeModel
        {
            [Required]
            public string Name { get; set; }
        }

    Controller

    public class HomeController : Controller
        {
            [HttpGet]
            public IActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            public IActionResult Index(HomeModel model)
            {
                if (ModelState.IsValid)
                {
    
                    return View(model);
                }
               
                return View(model);
            }
    	}

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 13, 2019 5:31 AM