I have the following CSHTML codes:
<div class="container-fluid projects padding-top-small">
<div class="row">
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="service1.html">
<img src="assets/img/portfolio/image1.jpg" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>Service 1</h3>
<p><small>Short Description 1</small></p>
</div>
</div>
</a>
</div>
</div>
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="service2.html">
<img src="assets/img/portfolio/image2.jpg" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>Service 2</h3>
<p><small>Short Description 2</small></p>
</div>
</div>
</a>
</div>
</div>
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="service1.html">
<img src="assets/img/portfolio/image3.jpg" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>Service 3</h3>
<p><small>Short Description 3</small></p>
</div>
</div>
</a>
</div>
</div>
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="service1.html">
<img src="assets/img/portfolio/image4.jpg" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>Service 4</h3>
<p><small>Short Description 4</small></p>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
Pretty much everything is hard-coded HTML tags.
I want to be able to render them dynamically.
In my controller, I am retrieving a list of Service Object comprised of the following items: SERVICE_URL, SERVICE_IMAGE_URL, SERVICE_NAME and SERVICE_DESCRIPTION. These list is stored in the ViewBag (Not sure if the viewbag is the best placeholder).
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="SERVICE_URL">
<img src="SERVICE_IMAGE_URL" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>SERVICE_NAME</h3>
<p><small>SERVICE_DESCRIPTION</small></p>
</div>
</div>
</a>
</div>
</div>
What I want to achieve is to have each div rendered dynamically, so that I would be able to show up only those services available.
Controller.cs
public class myService
{
public string service_url { get; set; }
public string service_image_url { get; set; }
public string service_name { get; set; }
public string service_description { get; set; }
}
private void loadServices()
{
List<myService> myServices = new List<myService>();
for(int i=0; i<3; i++)
{
myService msvc = new myService();
msvc.service_url = "service_url" + i.ToString() + ".html";
msvc.service_image_url = "image_url" + i.ToString() + ".jpg";
msvc.service_name = "Service " + i.ToString();
msvc.service_description = "Service Description " + i.ToString();
myServices.Add(msvc);
}
ViewBag.DataServices = myServices;
}
public ActionResult Home()
{
loadServices();
return this.RedirectToAction("Index", "Controller");
}
Rephrasing the question:
Given on my Controller that I have a list of the services and storing them to the ViewBag, how do I generate the DIVs on the Razor Page with the attributes as provided from the hard coded HTML?
I built a working prototype of this and will run you through the steps of each part. I then suggest you find some good basic books on MVC Razor programming and start from the beginning as there is a lot of detail to learn:
Use separate files for any classes and put models in the models folder.
Use proper standards-based naming/proper-casing of properties (leading caps for properties & classes, "CamelCase" generally)
e.g. Models\MyService.cs:
namespace WebApplication.Models
{
public class MyService
{
public string ServiceUrl { get; set; }
public string ServiceImageUrl { get; set; }
public string ServiceName { get; set; }
public string ServiceDescription { get; set; }
}
}
Your Home controller wants a Services action so the the URL routing is from the meaningful /Home/Services
Controllers\HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication5.Models;
namespace WebApplication.Controllers
{
public class HomeController : Controller
{
private List<MyService> LoadServices()
{
List<MyService> myServices = new List<MyService>();
for (int i = 0; i < 3; i++)
{
MyService msvc = new MyService();
msvc.ServiceUrl = "service_url" + i.ToString() + ".html";
msvc.ServiceImageUrl = "image_url" + i.ToString() + ".jpg";
msvc.ServiceName = "Service " + i.ToString();
msvc.ServiceDescription = "Service Description " + i.ToString();
myServices.Add(msvc);
}
return myServices;
}
public ActionResult Services()
{
// return a view using the ViewModel provided by LoadServices()
return View(LoadServices());
}
}
}
In the view, you need to declare the type of View Model being passed
You need to loop over the Model (which is an enumerable collection)
Using Razor syntax you inject the properties of the Model's elements
Views\Home\Services.cshtml:
#model IEnumerable<WebApplication.Models.MyService>
<div class="container-fluid projects padding-top-small">
<div class="row">
#foreach (var service in Model)
{
<div class="col-sm-6 col-md-3">
<div class="project-inner">
<a href="#service.ServiceUrl">
<img src="#service.ServiceImageUrl" alt="">
<div class="project-caption">
<div class="project-details">
<p><i class="fa fa-plus fa-lg"></i></p>
<h3>#service.ServiceName</h3>
<p><small>#service.ServiceDescription</small></p>
</div>
</div>
</a>
</div>
</div>
}
</div>
</div>
And the end result of all this work looks like this:
Related
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using eLearningHub.Core.DataModel.Base;
namespace eLearningHub.Core.DataModel
{
[Table("ClassEnroll")]
public class ClassEnroll : BaseModel
{
[Required]
public string Status { get; set; }
[ForeignKey("ClassModel")]
[DisplayName("Class")]
public int ClassId { get; set; }
public ClassModel ClassModel { get; set; }
[ForeignKey("TeacherModel")]
[DisplayName("Teacher")]
public int TeacherId { get; set; }
public TeacherModel TeacherModel { get; set; }
[ForeignKey("StudentModel")]
[DisplayName("Student")]
public int StudentId { get; set; }
public StudentModel StudentModel { get; set; }
}
}
the above code is the C# core datamodel.
cshtml code:
#model IEnumerable<eLearningHub.Core.DataModel.ClassEnroll>
#{
ViewBag.Title = "CourseListByStudent";
Layout = "~/Views/Shared/_DashBoard.cshtml";
}
<link href="~/Content/AdminLTE/Content/cardstyle.css" rel="stylesheet" />
#if (TempData["Msg"] != null)
{
<div class="col-lg-12">
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-info"></i> info!</h4>
#TempData["Msg"].ToString()
</div>
</div>
}
#if (TempData["FMsg"] != null)
{
<div class="col-lg-12">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-info"></i> Failed!</h4>
#TempData["FMsg"].ToString()
</div>
</div>
}
#foreach (var c in Model)
{
<div class="col-md-4">
<div class="box box-solid">
<div class="box-header with-border">
<i class="fa fa-graduation-cap width"></i>
<h3 class="box-title">Class Details</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<dl class="dl-horizontal">
<dt>Class Name : </dt>
<dd>#c.ClassModel.ClassName</dd>
<dt>Teacher : </dt>
<dd>#c.TeacherModel.Name</dd>
<dt> Email :</dt>
<dd> #c.TeacherModel.Email</dd>
<strong>Notes <i class="fa fa-sticky-note width"></i></strong>
<strong>Notice <i class="fa fa-bullhorn width"></i></strong>
<strong>Exam Mark <i class="fa fa-bullhorn width"></i></strong>
</dl>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
}
Let me further explain my issue, I am running a .net application that i have done, however, I have many cshtml pages and all connected to an sql DB, everything in the program works perfectly except for some pages, they simply won't load whatsoever and I cant figure out why that is happening,
I have also realized that all the pages that are not working or even loading (no error given, simple an empty page)
All the pages that are not opening have the same public class ClassEnroll
any tips ?
I am working on my college website project we created APIs for store data and retrieve data from the Database. Now I am integrating this API in to the admin panel but I don't know how to create a POST method or NewsAdd method.
This is my controller code.
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using BACKEND_HTML_DOT_NET.Models;
using Newtonsoft.Json;
using System.Text;
using RestSharp;
namespace BACKEND_HTML_DOT_NET.Controllers
{
public class News : Controller
{
private string apiBaseUrl = "https://localhost:44374/api";
HttpClient hc = new HttpClient();
private List<NewsVM> newsVMList = new List<NewsVM>();
public IActionResult NewsList()
{
var restClient = new RestClient(apiBaseUrl);
var restRequest = new RestRequest("/GetAllNewsDetails", Method.Get);
restRequest.AddHeader("Accept", "application/json");
restRequest.RequestFormat = DataFormat.Json;
RestResponse response = restClient.Execute(restRequest);
var content = response.Content;
var user = JsonConvert.DeserializeObject<ServiceResponse<List<NewsVM>>>(content);
newsVMList = user.data;
return View(newsVMList);
}
public IActionResult NewsView(int id=0)
{
NewsVM newsVM = new NewsVM();
newsVM = newsVMList.Where(m => m.Id == id).FirstOrDefault();
return View(newsVM);
}
public IActionResult NewsAdd()
{
return View();
}
}
}
This is my cshtml page
#model List<BACKEND_HTML_DOT_NET.Models.NewsVM>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "NewsAdd";
}
<div class="content-wrapper">
<!-- <h3 style="margin-left: 15px;">DEPARTMENT</h3> -->
<section class="content" style="margin-top:20px;">
<div class="row">
<div class="col-md-12">
<a href="#Url.Action("NewsList","News")">
<ol class="breadcrumb float-sm-right">
<li style="margin-left: 00px;"><i class="nav-icon fas fa-minus-circle"></i></li>
<li style="margin-left: 00px;">Back to Details</li>
</ol>
</a>
</div>
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Add New News</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form id="newsaddform" asp-action="NewsAdd" asp-controller="News" method="post" role="form">
#using(Html.BeginForm()){
<div class="card-body">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="exampleInputText">ENTER TITLE OF NEWS</label>
<input type="text" name="title" class="form-control" id="exampleInputEmail1" placeholder="ENTER TITLE.. ">
</div>
</div>
<div class="col-md-6">
<label for="description">ENTER DESCRIPTION OF NEWS</label>
<textarea type="text" name="description" class="form-control" id="description" rows="4" placeholder="Write content"></textarea>
</div>
</div>
</div>
<div class="card-footer">
<div class="input-group col-12">
<div class="col-sm-6"><button type="submit" id="sub" class="btn btn-primary float-right col-md-2">Submit</button></div>
<div class="col-sm-6"><button type="reset" class="btn btn-default col-md-2">Clear</button></div>
</div>
</div>
}
</form>
</div>
</div>
<!-- /.card-body -->
</div>
</section>
</div>
#section script{
<script type="text/javascript">
$(document).ready(function() {
//console.log( "ready!" );
$('#newsaddform').validate({
rules: {
"title": {
required: true
},
"description": {
required: true
}
},
messages: {
"title": {
required: "this field is required"
},
"description": {
required: "this field is required"
}
}
});
$('#newsaddform').submit(function(e) {
//prevent Default functionality
e.preventDefault();
if($('#newsaddform').valid()){
var dataForm = new FormData($('#newsaddform')[0]);
$.ajax({
url: '#Url.Action("NewsAdd","News")',
type: 'post',
crossDomain: true,
enctype: 'multipart/form-data',
dataType: 'application/json',
processData: false,
contentType: false,
data: dataForm,
success: function(data) {
console.log(data);
}
});
}
});
});
</script>
}
This is the model class
using System;
using System.Collections.Generic;
namespace BACKEND_HTML_DOT_NET.Models
{
public class NewsVM
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime Date { get; set; }
public bool? IsDeleted { get; set; }
public DateTime? CreatedDate { get; set; }
public string CreatedDateInt { get; set; }
public DateTime? UpdatedDate { get; set; }
public string UpdatedDateInt { get; set; }
}
}
When you select form submit(method="post"),you can send the post request directly by clicking the Submit button(type="submit"), this will submit the content of your input box by default,and don't need to send the post request through Ajax.
Below is my test code,you can refer to it:
View:
#model _2022072601.Models.NewsVM
<div class="content-wrapper">
<!-- <h3 style="margin-left: 15px;">DEPARTMENT</h3> -->
<section class="content" style="margin-top:20px;">
<div class="row">
<div class="col-md-12">
<a href="#Url.Action("NewsList","News")">
<ol class="breadcrumb float-sm-right">
<li style="margin-left: 00px;"><i class="nav-icon fas fa-minus-circle"></i></li>
<li style="margin-left: 00px;">Back to Details</li>
</ol>
</a>
</div>
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Add New News</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form id="newsaddform" asp-action="NewsAdd" asp-controller="Home" method="post" role="form">
#using(Html.BeginForm()){
<div class="card-body">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="exampleInputText">ENTER TITLE OF NEWS</label>
<input type="text" name="title" class="form-control" id="exampleInputEmail1" placeholder="ENTER TITLE.. ">
</div>
</div>
<div class="col-md-6">
<label for="description">ENTER DESCRIPTION OF NEWS</label>
<textarea type="text" name="description" class="form-control" id="description" rows="4" placeholder="Write content"></textarea>
</div>
</div>
</div>
<div class="card-footer">
<div class="input-group col-12">
<div class="col-sm-6"><button type="submit" id="sub" class="btn btn-primary float-right col-md-2">Submit</button></div>
<div class="col-sm-6"><button type="reset" class="btn btn-default col-md-2">Clear</button></div>
</div>
</div>
}
</form>
</div>
</div>
<!-- /.card-body -->
</div>
</section>
</div>
Controller:
[HttpGet]
public IActionResult NewsAdd()
{
return View();
}
[HttpPost]
public JsonResult NewsAdd(NewsVM newsVM)
{
return Json(newsVM);
}
Test Result:
For more details, please refer to this link.
When I try to get data from data for edit page it's showing me the following error:
So I am building a website where I want to implement a edit banner form when the User can Edit his banner data.
And here is where the problem I raise, when I run the code, it return always as null.
Here is my controller:
[HttpGet]
public ActionResult EditBanner(int id)
{
var abd = (from a in _db.Banner
where id == a.BannerId
select a).FirstOrDefault();
return View(abd);
}
[HttpPost]
public ActionResult UpdateBannerDatas(BannerViewModels bnrupdate)
{
var bnrdata = _db.Banner.Where(x => x.BannerId == bnrupdate.BannerId).FirstOrDefault();
if (bnrdata != null)
{
bnrdata.BannerTitle = bnrupdate.BannerTitle;
bnrdata.BannerUrl = bnrupdate.BannerUrl;
bnrdata.BannerIndex = bnrupdate.BannerIndex;
bnrdata.BannerDescription = bnrupdate.BannerDescription;
bnrdata.BannerIndex = bnrupdate.BannerIndex;
_db.SaveChanges();
}
return Redirect("BannerDetails");
}
Here is my viewmodel:
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SZGMC.Web.Models;
namespace SZGMC.Web.Areas.Admin.ViewModels
{
public class BannerViewModels
{
public int BannerId { get; set; }
public string BannerTitle { get; set; }
public string BannerDescription { get; set; }
public string BannerImg { get; set; }
public IFormFile BannerImg1 { get; set; }
public string BannerUrl { get; set; }
public string BannerIndex { get; set; }
public int? BMasterId { get; set; }
public byte? IsDeleted { get; set; }
public virtual BannerMaster BMaster { get; set; }
}
}
Here is my model:
using System;
using System.Collections.Generic;
// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable
namespace SZGMC.Web.Models
{
public partial class Banner
{
public int BannerId { get; set; }
public string BannerTitle { get; set; }
public string BannerDescription { get; set; }
public string BannerImg { get; set; }
public string BannerUrl { get; set; }
public string BannerIndex { get; set; }
public int? BMasterId { get; set; }
public byte? IsDeleted { get; set; }
public virtual BannerMaster BMaster { get; set; }
}
}
Here is my view:
<form asp-controller="Home" asp-action="UpdateBannerDatas" enctype="multipart/form-data" method="post">
<div id="main-content">
<div class="container-fluid">
<!-- Page header section -->
<div class="block-header">
<div class="row clearfix">
<div class="col-lg-6 col-md-5 col-sm-12">
<h1>Hi, Welcomeback!</h1>
<span>You can edit banner here</span>
</div>
<div class="col-xl-6 col-md-7 col-sm-12 text-md-right">
<div class="d-flex align-items-center justify-content-md-end mt-4 mt-md-0 flex-wrap vivify pullUp delay-550">
<div class="mb-3 mb-xl-0 ">
<a asp-action="BannerDetails" class="btn btn-dark">Banner List</a>
</div>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-12">
<div class="card">
<div class="body">
<div class="header">
<h2><strong>Enter Banner Details</strong></h2>
</div>
<br />
<input asp-for="BannerId" type="hidden" />
<div class="row">
<div class="col-12">
<div class="form-group c_form_group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="text" class="form-control" asp-for="BannerTitle" placeholder="Banner Title" aria-label="bannertitle" aria-describedby="basic-addon1">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group c_form_group">
<label>Banner Description</label>
<div class="input-group">
<textarea class="form-control" asp-for="BannerDescription" aria-label="Banner Description" rows="6"></textarea>
</div>
</div>
</div>
<div class="col-6">
<div class="drop-zone">
<span class="drop-zone__prompt">Drop file here or click to upload</span>
<input type="file" asp-for="BannerImg1" name="myFile" class="drop-zone__input" accept="image/*" data-allowed-file-extensions='["jpg", "png" , "jpeg"]' required>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group c_form_group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="text" class="form-control" asp-for="BannerIndex" placeholder="Banner Index" aria-label="bannerindex" aria-describedby="basic-addon1">
</div>
</div>
</div>
<div class="col-6">
<div class="form-group c_form_group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
</div>
</div>
</div>
</div>
<div class="mb-2" align="center">
<button type="submit" class="btn btn-success btn-round">Edit Banner</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
When i try To Edit the data in the browser it Throw exception, in database i have value but when i tried to fetch data its showing error.
thank you in advance to everybody for any help or advice.
According to the error message it is necessary to pass the BannerViewModels instance instead of the Banner entity:
public ActionResult EditBanner(int id)
{
var abd = _db.Banner.Where(a => a.BannerId == id)
.Select(b => new BannerViewModels()
{
BannerId = b.BannerId,
BannerTitle = b.BannerTitle,
BannerDescription = b.BannerDescription,
BannerImg = b.BannerImg,
BannerUrl = b.BannerUrl,
BannerIndex = b.BannerIndex,
BMasterId = b.BMasterId,
IsDeleted = b.IsDeleted
})
.FirstOrDefault();
return View(abd);
}
Passing an entity to the view as a data model is bad idea.
See the following post: Why it's not a good idea to pass entities as Models in MVC?
I´m experiencing a very strange behaviour with ASP .net core 2.2 Razor Pages.
Let´s say I have a standard Razor Page. The User can send a request over that page for a new Team that should be provisioned. I have some fields like, DisplayName etc. which the user can edit freely and a dropdown to choose from where he can select from which existing Team he would like to clone some settings from. After the User selected it, I´m using Ajax to render the partial View on the right side of the view and the User can also select some additional options. Until here I´m fine and everything is working so far. I expected, if the user clicks the save / submit button that everything will be included in the post request, even the partial View Data. After digging around and troubleshooting I found out that I have to set ViewData.TemplateInfo.HtmlFieldPrefix to name everything like in the Parent View to not mess the Binding up. Works also.
The strange behaviour is, that after the Partial View was rendered, in HTML two Inputs fields were generated. One where the user can select and one which is hidden. I´ll show my code and also the rendered HTML File so that guys can make yourself a picture of that. What now happens is, the hidden fields have a default or null values and these are going to be included in the request. I have no idea where they come from and / or how to fix it or what I did wrong?
I will shorten my code a little bit but I will include the necessary parts.
Team Request Model
public class TeamRequestModel
{
public string DisplayName { get; set; }
public string Description { get; set; }
public string Visibility { get; set; }
public List<string> Owners { get; set; }
public string CloneTeamID { get; set; }
public TeamCloneSettings TeamCloneSettings { get; set; }
public TeamRequestModel()
{
TeamCloneSettings = new TeamCloneSettings();
}
}
Team Clone Settings (only Parts can be Set by the user
public class TeamCloneSettings
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
public string PartitionKey;
public string DisplayName { get; set; }
public bool Released { get; set; }
public bool FixedVisibility { get; set; }
public string Visibility { get; set; }
public bool CloneEverything { get; set; }
public TeamCloneParts Parts { get; set; }
public TeamCloneSettings()
{
Parts = new TeamCloneParts();
}
}
public class TeamCloneParts
{
public bool CloneApps { get; set; }
public bool CloneChannels { get; set; }
public bool CloneTabs { get; set; }
public bool CloneSettings { get; set; }
}
}
Main "Team Request View"
#page
#model iwDashboard.Pages.Teams.TeamRequest
#{
ViewData["Title"] = Model.Title;
}
#{
ViewBag.PageTitle = Model.Title;
}
<style>
textarea {
resize: none;
}
</style>
<section class="content">
<form method="post" asp-page-handler="SaveTeamRequest" class="col-md-12">
<div class="row">
<div class="col-md-3">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Team Details</h3>
</div>
<div class="card-body">
<div class="form-group">
<label for="displayName">Display Name</label>
<input id="displayName" asp-for="#Model.teamRequest.DisplayName" type="text" class="form-control" required />
</div>
... More fields
<div style="float: left; width: 40%">
<button type="button" onclick="history.go(-1)" data-toggle="tooltip" title="Back" class="btn btn-primary btn-block btn-sm"><i class="fa fa-arrow-circle-left"></i><b> Back</b></button>
</div>
<div style="float: right; width: 40%">
<button type="submit" data-toggle="tooltip" title="Save" class="btn btn-success btn-block btn-sm"><i class="fas fa-save"></i><b> Save</b></button>
</div>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<div class="col-md-6">
<div class="card card-secondary">
<div class="card-header">
<h3 class="card-title">Team Settings</h3>
</div>
<div class="card-body">
<!--partial comes here-->
<div id="partialDiv"></div>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</div>
</form>
</section>
#section Scripts
{
<script>
function GetTeamTemplateProperties() {
var selectedTeam = $('#teamTemplateSelection').val();
$.ajax({
type: "Get",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: '/Teams/TeamRequest?handler=TeamTemplateProperties',
data: {
SelectedTeam: selectedTeam
},
success: function (result) {
$("#partialDiv").after(result);
}
})
};
</script>
}
Get Template Properties Post called by Ajax
public async Task<IActionResult> OnGetTeamTemplateProperties(string SelectedTeam)
{
TeamCloneSettings teamCloneSettings = new TeamCloneSettings();
teamRequest = new TeamRequestModel();
if (!string.IsNullOrEmpty(SelectedTeam))
{
teamCloneSettings = await _teamCloneSettingService.GetTeamCloneSettingByIdAsync(SelectedTeam);
teamRequest.TeamCloneSettings = teamCloneSettings;
}
ViewData.TemplateInfo.HtmlFieldPrefix = "teamRequest";
SelectedValue = SelectedTeam;
return new PartialViewResult
{
ViewName = "_TeamCloneSettingsPartial",
ViewData = new ViewDataDictionary<TeamRequestModel>(ViewData, teamRequest)
};
}
View Model BindProperty
...More Code
[BindProperty]
public TeamRequestModel teamRequest { get; set; }
[BindProperty]
public string SelectedValue { get; set; }
...More Code
_TeamCloneSettingsPartial
#model iwDashboard.Models.TeamRequestModel
#{
<!--
Check if fixed visibility is enabled and
disable selection of visibility if it is
-->
string disabled = null;
string options = null;
if (Model.TeamCloneSettings.FixedVisibility)
{
disabled = "disabled";
options = Model.Visibility;
}
}
<div class="form-group">
<input type="checkbox" hidden id="cloneEverthing" checked=#Model.TeamCloneSettings.CloneEverything>
<ul class="list-group list-group-unbordered mb-3">
<li class="list-group-item">
<label for="visibility">Visibility</label>
<select class="form-control #disabled custom-select" asp-for="TeamCloneSettings.Visibility" required>
#if (!string.IsNullOrEmpty(disabled))
{
<option readonly selected>#Model.TeamCloneSettings.Visibility</option>
}
else
{
<option>Public</option>
<option>Private</option>
}
</select>
</li>
<!-- Checkbox parts here
Javascript will check if "CloneEverything"
is enabled and will disable all of the following checkboxes
-->
<li class="list-group-item">
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="cloneApps" checked=#Model.TeamCloneSettings.Parts.CloneApps asp-for="TeamCloneSettings.Parts.CloneApps">
<label class="custom-control-label" for="cloneApps">Clone Apps</label>
</div>
</div>
</li>
<li class="list-group-item">
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="cloneChannels" checked=#Model.TeamCloneSettings.Parts.CloneChannels asp-for="TeamCloneSettings.Parts.CloneChannels">
<label class="custom-control-label" for="cloneChannels">Clone Channels</label>
</div>
</div>
</li>
<li class="list-group-item">
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="cloneSettings" checked=#Model.TeamCloneSettings.Parts.CloneSettings asp-for="TeamCloneSettings.Parts.CloneSettings">
<label class="custom-control-label" for="cloneSettings">Clone Settings</label>
</div>
</div>
</li>
<li class="list-group-item">
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="cloneTabs" checked=#Model.TeamCloneSettings.Parts.CloneTabs asp-for="TeamCloneSettings.Parts.CloneTabs">
<label class="custom-control-label" for="cloneTabs">Clone Tabs</label>
</div>
</div>
</li>
</ul>
</div>
Strange rendered Input field
https://i.stack.imgur.com/aZtUD.png
As you can see, the Input is rendered twice and only the hidden values will be transmitted. But this only happens for the Input fields in the Partial View, all other fields are fine.
Any Ideas? Would be great :-).
Thanks a lot!!
Having 2 input fields generated is normal when using the asp-for tag helper on a checkbox. It will create the checkbox itself but also a hidden input field for the model binder to send the value chosen by the user.
Only the hidden field generated by the tag helper will be used to send the data.
Found a solution here:
asp.net mvc: why is Html.CheckBox generating an additional hidden input
Might not be the best one but it works for me:
checking with Javascript if the Checkbox is selected an then setting the value of the hidden field:
if ($('[name="foo"]:checked').length > 0)
$('[name="foo"]:hidden').val(true);
Thanks everybody!
I want to use a different model for my partialviews, how to do this? Do you have examples?
<div id="tabs">
<ul>
<li>first tab</li>
<li>second tab</li>
<li>third tab</li>
</ul>
<div id="tabs-1">
#{Html.RenderPartial("FirstTabView", Model)}
</div>
<div id="tabs-2">
#{Html.RenderPartial("SecondTabView", Model)}
</div>
<div id="tabs-3">
#{Html.RenderPartial("ThirdTabView", Model)}
</div>
</div>
You could have sub-models as part of your main model, such as:
public class YourModel
{
public FirstTabModel FirstTab { get; set; }
public SecondTabModel SecondTab { get; set; }
public ThirdTabModel ThirdTab { get; set; }
}
Then you can do:
<div id="tabs-1">
#{Html.RenderPartial("FirstTabView", Model.FirstTab)}
</div>
<div id="tabs-2">
#{Html.RenderPartial("SecondTabView", Model.SecondTab)}
</div>
<div id="tabs-3">
#{Html.RenderPartial("ThirdTabView", Model.ThirdTab)}
</div>