Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • DEV 12 posts 102 karma points
    Apr 04, 2019 @ 11:05
    DEV
    0

    How to include Umbraco Template to Custom view or Using @inherits UmbracoTemplatePage<IPublishedContent> and Custom model

    Hi,

    I want to add Umbraco Template page to my Custom view.but i cannot do it.

    1.I can not create Country view model object in controller (CountryViewModel test = new CountryViewModel ();) .so i cannot pass model to view. How can achieve that

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    After Include @inherits Umbraco.Web.Mvc.UmbracoTemplatePage it shows following Error Page

    enter image description here

    enter image description here

    Regards,

    DEV

  • Marc Goodson 2128 posts 14220 karma points MVP 8x c-trib
    Apr 04, 2019 @ 19:13
    Marc Goodson
    0

    Hi DEV

    Have a look at Route Hijacking in the documentation - https://our.umbraco.com/Documentation/Reference/Routing/custom-controllers-v7

    Essentially Umbraco by default (in V7) maps every incoming request to a default MVC controller called RenderMvcController that returns a model called RenderModel, so you are seeing your error because this default RenderModel doesn't know anything about your custom CountryViewModel...

    You have your custom view model defined correctly, and your inherits statement also looks good to say that's the kind of model I want to use with the view... but nothing is telling Umbraco at the controller stage that it needs to create your custom view model!

    The route hijacking technique to do this relies on convention, if you create a controller that matches the document type alias of the page you want to work with, then this controller will become responsible for handling all requests to that document type, and you can create your custom view model accordingly.

    So create a new MVC controller like so: (where DocTypeAlias is the alias of the document type in question)

    public class DocTypeAliasController : Umbraco.Web.Mvc.RenderMvcController
    {
        public override ActionResult Index(RenderModel model)
        {
            ///create your Custom View Model
    CountryViewModel vm = new CountryViewModel(model.Content);
    //populate the custom properties on our view model...
    
    //pass the viewmodel to the current template
            return CurrentTemplate(vm);
        }
    }
    

    Now the correct model type should be passed to your View!

    regards

    Marc

  • DEV 12 posts 102 karma points
    Apr 05, 2019 @ 04:46
    DEV
    0

    Dear marc,

    This is my Controller code below

    using Umbraco.Web.Mvc;

    using Umbraco.Web.Models;

    using System.Web.Mvc;

    using umbracotest.Models;

    using System.Net.Mail;

    using System.Data;

    using System.Data.SqlClient;

    using System.Web.Mvc;

    using System.Configuration;

    using System.Collections;

    using System.Collections.Generic;

    using System;

    namespace umbracotest.Controllers

    {

    public class CountrySurfaceController : SurfaceController
    {
    
         [HttpGet]      
       public ActionResult _CitiCountryEdit(string Countryid)
        {
           try
           {              
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["umb"].ConnectionString);  
            connection.Open();  
            List<CountryModel> lstcountry = new List<CountryModel>();           
            CountryModel item = new CountryModel();             
            DataSet DS = new DataSet();         
            String qry = String.Format("Select * from cmsCountry Where Countryid ='{0}'",Convert.ToInt32(Countryid));
            SqlCommand cmd = new SqlCommand(qry,connection);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(DS);           
                if(DS.Tables.Count>0)
                {                    
                  if(DS.Tables[0].Rows.Count > 0)
                    {
                      foreach (DataRow Res in DS.Tables[0].Rows)
                      {
                        //CountryModel item = new CountryModel();
                        item.Countryid = Convert.ToInt32(Res["Countryid"]);
                        item.Countryname = Convert.ToString(Res["Countryname"]);
                        item.Status = Convert.ToBoolean(Res["Status"]); 
    
                      }
                    }
                }
                //CountryViewModel.country  = item;     
                //CountryViewModel country = new CountryViewModel();
                var countryview = item;            
    return View(PARTIAL_VIEW_FOLDER+"_CitiCountryEdit.cshtml",countryview);
           }
           catch (Exception e)
           {
               throw e;
           }
        }
    
     }
    

    }

    [ HttpPost]

        [ValidateAntiForgeryToken]
    
        public ActionResult _CitiCountryEdit(CountryModel model,string Countryid)
        {
            try
            {
                 if (ModelState.IsValid)
            {
    
                SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["umb"].ConnectionString);  
                connection.Open();  
                String updatequery = String.Format("update cmsCountry set Countryname=@Countryname,Status=@Status where Countryid = @Countryid");
                SqlCommand cmd = new SqlCommand(updatequery,connection);
                cmd.Parameters.AddWithValue("@Countryname", model.Countryname);
                cmd.Parameters.AddWithValue("@Status", model.Status);
                cmd.Parameters.AddWithValue("@Countryid", Convert.ToInt32(Countryid));
                int rowsDeletedCount = cmd.ExecuteNonQuery();
    
                TempData["ContactSuccess"] = true;
    
                return Redirect("");               
            }
            return Redirect("");
    
            }
            catch (Exception e)
            {               
                throw e;                
            }
        }
    

    Models:

    namespace umbracotest.Models

    {

    public class CountryViewModel : RenderModel
    {
        public CountryViewModel() : this(new UmbracoHelper(UmbracoContext.Current).TypedContent(UmbracoContext.Current.PageId)) { }
        public CountryViewModel(IPublishedContent content, CultureInfo culture) : base(content, culture) { }
        public CountryViewModel(IPublishedContent content) : base(content) { }
        public CountryModel country;
        public string Countryname { get; set; }
        public bool Status { get; set; }
        public int Countryid { get; set; }
        public IEnumerable<CountryModel> CountryModel { get; set; }
    }
    
     public class CountryModel
    {
        [Display(Name = "Country Id:")]
        public int Countryid { get; set; }
    
        [Required]
        [Display(Name = "Country Name:")]
        public string Countryname { get; set; }        
    
        [Required]
        [Display(Name = "Status")]
        public bool Status { get; set; }
    
    }
    

    }

    View:

    @inherits Umbraco.Web.Mvc.UmbracoViewPage

    @using (Html.BeginUmbracoForm("UpdateForm", "CountrySurface", FormMethod.Post))

    {

    @Html.AntiForgeryToken()
    
    <div class="form-group">
        @Html.ValidationSummary()
    </div>
    
    <div class="form-group">
        <div class="col-xs-6">
            @Html.LabelFor(m => m.country.Countryname)
        </div>
        <div class="col-xs-9">
            @Html.TextBoxFor(m => m.country.Countryname)
        </div>
    </div>
    
    <div class="form-group">
        <div class="col-xs-6">
            @Html.LabelFor(m => m.country.Status)
        </div>
        <div class="col-xs-9">
             @Html.DropDownListFor(m => m.country.Status, new List<SelectListItem>
                                  { new SelectListItem{Text="Active", Value="True"},
                                  new SelectListItem{Text="Inactive", Value="False"}, }, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
    <div class="col-xs-9">
    <button>Update</button>
    <button id="btnback">Back</button>
    </div>
    </div>
    

    but I am used to Surface controller.How can i achieve to inherit template page to view using RenderMVC Controller.

  • Marc Goodson 2128 posts 14220 karma points MVP 8x c-trib
    Apr 05, 2019 @ 10:17
    Marc Goodson
    0

    Hi DEV

    Yes you need to create an MVC controller inheriting from RenderMvcController.

    What is the alias of the Document Type of the page this code is executed on?

    You will need to name your Controller:

    aliasController : RenderMvcController

    where the alias matches the DocumentType.

    Create an Index action on this controller

    and then create your custom view model inside the Index action, and populate any properties (the bit you are currently doing in a surface controller)... sending this enriched viewmodel to your view, using return CurrentTemplate

    public class aliasController : Umbraco.Web.Mvc.RenderMvcController
    {
        public override ActionResult Index(RenderModel model)
        {
            ///create your Custom View Model
    CountryViewModel vm = new CountryViewModel(model.Content);
    //populate the custom properties on our view model...
    
    //pass the viewmodel to the current template
            return CurrentTemplate(vm);
        }
    }
    

    Your form postback should still be handled by a SurfaceController.

    regards

    marc

  • DEV 12 posts 102 karma points
    Apr 05, 2019 @ 11:10
    DEV
    0

    Hi Marc,

    I have little Confusion.Whether Create New Controller in Separately or worked in Previous one.Below I have Create New Controller. But when click Edit link in Country List(view) it shows Link Wrongly (http://umbraco.test/citicountry). How can i achieve this.

    Country MVC Controller:

    namespace umbracotest.Controllers { public class CountryMVCController : Umbraco.Web.Mvc.RenderMvcController {

      #region Private Variables   
    
        public const string PARTIAL_VIEW_FOLDER = "~/Views/Partials/CitiCountry/";
    
    
    
        public override ActionResult Index(RenderModel model)
           {
               ///create your Custom View Model
             CountryViewModel vm = new CountryViewModel(model.Content);
            //populate the custom properties on our view model...
    
             //pass the viewmodel to the current template
               return CurrentTemplate(vm);
            }    
    
    
    
    
       public ActionResult _CitiCountryEdit(string Countryid)
        {
           try
           {              
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ConnectionString);  
            connection.Open();  
            List<CountryModel> lstcountry = new List<CountryModel>();           
            CountryModel item = new CountryModel();             
            DataSet DS = new DataSet();         
            String qry = String.Format("Select * from cmsCountry Where Countryid ='{0}'",Convert.ToInt32(Countryid));
            SqlCommand cmd = new SqlCommand(qry,connection);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(DS);           
                if(DS.Tables.Count>0)
                {                    
                  if(DS.Tables[0].Rows.Count > 0)
                    {
                      foreach (DataRow Res in DS.Tables[0].Rows)
                      {
                        //CountryModel item = new CountryModel();
                        item.Countryid = Convert.ToInt32(Res["Countryid"]);
                        item.Countryname = Convert.ToString(Res["Countryname"]);
                        item.Status = Convert.ToBoolean(Res["Status"]); 
    
                      }
                    }
                }
                //CountryViewModel.country  = item;     
                //CountryViewModel country = new CountryViewModel();
                var countryview = item;            
            return View(PARTIAL_VIEW_FOLDER+"_CitiCountryEdit.cshtml",countryview);
           }
           catch (Exception e)
           {
               throw e;
           }
        }
    
    
    
    
    }
    

    Country List:

    @model List

    Country Name Action @{ foreach(var country in Model.ToList()) { @country.Countryname Edit | Delete @Html.ActionLink("Edit","_CitiCountryEdit","CountryMVC", new { [email protected] } ,null) } }
Please Sign in or register to post replies

Write your reply to:

Draft