Partial View returning null model - c#

Now I bet this is a problem that happens often, I just can't seem to find anything related to it, or notice myself what is wrong with it. The view provided at bottom always returns null on foreach line.
I'm making a simple currency list.
Model:
public class Currency
{
public int ID { get; set; }
public string Name { get; set; }
public string Sign { get; set; }
public float BuyValue { get; set; }
public float MidValue { get; set; }
public float SellValue { get; set; }
public string CurrencyIcon { get; set; }
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime DateCreated { get; set; }
}
And it should be posted as partial view, on several different ways so to say. For example, partial view that will get all of them (for today), and partial view that will get random 6 (also for today).
I'm doing the first part now, all of them, for today.
Controller
public ActionResult FrontPagePartial()
{
DateTime today = DateTime.Now.Date; //i'm filtering it by date only
var currencies = db.Currencies.Where(c => c.DateCreated.Equals(today));
return View(currencies);
}
I've checked the filtering it's working correctly. So my view goes like this:
#model IEnumerable<CurrencyList.Models.Currency>
<div id="currencyList_Partial">
<div id="bg_currencyList_Partial">
<img src="#Url.Content("~/Content/Resources/img.png")" />
</div>
<div id="header_currencyList_Partial">
<div style="padding: 10px;">
<p style="font-size: 18px;">
Currency List<br />
<span class="header_currencyList_Partial_Day">FOR TODAY</span>
</p>
<p class="header_currencyList_Partial_Link" >
DETAILS >
</p>
</div>
<div id="table_currencyList">
#foreach (var item in Model)
{
<table>
<tr>
<td style="text-align: center;"><img src='#item.CurrencyIcon' title='#item.Sign' /><p style="font-size: small;">#Html.DisplayFor(modelItem => item.Name)</p><p>#Html.DisplayFor(modelItem => item.Sign)</p></td>
<td style="text-align: center;">#Html.DisplayFor(modelItem => item.BuyValue)</td>
<td style="text-align: center;">#Html.DisplayFor(modelItem => item.MidValue)</td>
<td style="text-align: center;">#Html.DisplayFor(modelItem => item.SellValue)</td>
</tr>
</table>
}
</div>
</div>
</div>
Parent view
#{
ViewBag.Title = "Currency List Home Page";
}
#section HeadSection{
<link rel="stylesheet" href="#Url.Content("~/Content/layerslider.css")" type="text/css" media="screen" />
<link rel="stylesheet" href="#Url.Content("~/Content/defaultskin/skin.css")" type="text/css" media="screen" />
<noscript>
<link rel="stylesheet" href="#Url.Content("~/Content/noscript.css")" type="text/css" media="screen" />
</noscript>
}
#section ScriptSection{
<script src="#Url.Content("~/Scripts/jqueryui.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/plugins.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/page.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/layerslider.kreaturamedia.jquery.js")" type="text/javascript"></script>
}
<div id="content">
<div id="statusbar"></div>
<div id="slider">
<div id="layerslider">
<div class="ls-layer" style="slidedelay: 3000">
<img class="ls-bg" src="#Url.Content("~/Content/images/slider_gallery/slide1_layer1.png")" alt="layer" />
<img class="ls-s2" src="#Url.Content("~/Content/images/slider_gallery/behind_text_layer.png")" alt="sublayer" style="durationin: 0; top: 247px;/*easingin: easeOutElastic*/" />
<img class="ls-s3" src="#Url.Content("~/Content/images/slider_gallery/text_layer1.png")" alt="sublayer" style="durationin: 2000; top: 255px;left: 15px; easingin: easeOutElastic " />
</div>
<div class="ls-layer" style="slidedelay: 3000">
<img class="ls-bg" src="#Url.Content("~/Content/images/slider_gallery/slide2_layer1.png")" alt="layer" />
<img class="ls-s2" src="#Url.Content("~/Content/images/slider_gallery/behind_text_layer.png")" alt="sublayer" style="durationin: 0; top: 247px;/*easingin: easeOutElastic*/" />
<img class="ls-s3" src="#Url.Content("~/Content/images/slider_gallery/text_layer1.png")" alt="sublayer" style="durationin: 2000; top: 255px;left: 15px;easingin: easeOutElastic " />
</div>
<div class="ls-layer" style="slidedelay: 3000">
<img class="ls-bg" src="#Url.Content("~/Content/images/slider_gallery/slide3_layer1.png")" alt="layer" />
<img class="ls-s2" src="#Url.Content("~/Content/images/slider_gallery/behind_text_layer.png")" alt="sublayer" style="durationin: 0;top: 247px;" />
<img class="ls-s3" src="#Url.Content("~/Content/images/slider_gallery/text_layer1.png")" alt="sublayer" style="durationin: 2000; top: 255px; left: 15px; easingin: easeOutElastic " />
</div>
</div>
</div>
<div id="converter">
<h2>CONVERTER</h2>
<p class="shadowedText">
VALUE:
</p>
<p>
<input type="text" id="tb11" class="tb11" />
</p>
<p class="shadowedText">
FROM CURRENCY
</p>
<div class="select1 select1p">
<select id="select1">
<option>EUR - EURO</option>
<option> $ - DOLLAR</option>
</select>
<span class="selectArrow"><img src="#Url.Content("~/Content/images/select_arrows.png")" /></span>
</div>
<p class="shadowedText">
TO CURRENCY
</p>
<div class="select1 select1p">
<select id="select2">
<option> $ - EURO</option>
<option> EURO - DOLLAR</option>
</select>
<span class="selectArrows"><img src="#Url.Content("~/Content/images/select_arrows.png")" /></span>
</div>
<div class="select1p addMargin">
<span class="boldResult">100 EUR = 11710.55 $</span><br />
<span class="lightResult">100 $ = 0.84882 EUR</span>
</div>
</div>
</div>
<div id="lowerContent">
<div id="blog"><img src="#Url.Content("~/Content/images/vesti.png")" /></div>
//This is where Partial View is rendered
<div id="listC">#Html.Partial("FrontPagePartial")</div>
</div>
<div id="portals">
</div>

<div id="listC">#Html.Partial("FrontPagePartial")</div>
This is trying to render the partial view, FrontPagePartial, with the model of the parent view, which is not defined.
public ActionResult FrontPagePartial()
This creates an action so you can go, siteurl/controller/FrontPagePartial
What you need to do is
<div id="listC">#Html.Partial("FrontPagePartial", currencies)</div>
If you don't mind ViewBag, you can set ViewBag.Currencies in the Action method and
<div id="listC">#Html.Partial("FrontPagePartial", ViewBag.Currencies)</div>

The #Html.Partial just renders the html partial directly from the file view (in the Shared folder, not through the FrontPagePartial method in the controller) using the model that the parent owns. In your case Razor try to use the Model from the parent view but apparently you never defined it. That's the reason for the null object
#foreach (var item in Model) { ... }
You want to call a partial view that returns another kind of object model; that's not possible with #Httml.Partial nor #Html.RenderPartial. Two solutions:
Ajax call:
$(document).ready(function() {
$.get('#Url.Action("FrontPagePartial")',null,function(data) {
$('#listC').html(data);
});
});
Using Html.RenderAction or Html.Action:
<div id="listC">#Html.RenderAction("FrontPagePartial")</div>
Don't forget to change the return in the FrontPagePartial method. Without this the result will be the list of currencies inside the layout page (you are returning a simple page, not a partial view):
public ActionResult FrontPagePartial()
{
....
return PartialView(currencies);
}

Related

Search with multiple fields in asp.net core mvc

I create form where I get data from database using sql queries in asp.net core mvc. Now I want to search data with multiple fields like price, area, areaUnit . I am new to c# Kindly help me to search data and display. Data display in other div. In that div I make cards and get data from database using foreachloop.
MY view :
#model IEnumerable<eHouse.Models.RentModel>
<form>
<div class="wrap">
<div class="search">
<input type="text" class="searchTerm" style="width: 700px; color:#000000; text-align: left;" placeholder="Search Houses" onclick="filterfunction()">
<button type="submit" class="searchButton" >
<i class="fa fa-search"></i>
</button>
</div>
<div id="filter">
<select>
<option value="Kanal">Kanal</option>
<option value="Marla">Marla</option>
<option value="Square Feet">Square Feet</option>
<option value="Square Meter">Square Meter</option>
<option value="Square Yards">Square Yards</option>
</select>
<input type="text" placeholder="area" />
<input type="text" placeholder="price" />
</div>
</div>
</form>
<div class="property_information" >
#foreach (var item in Model)
{
<div class="home-info">
<span id="houseid">
</span>
<a href="#" class="home-images">
<img src="#item.pic1" />
</a>
<div class="home-data">
<div class="home-name">
<p>#item.tittle</p>
</div>
<div class="price">
<p>#item.price</p>
</div>
<div class="features">
<span>
#item.bedroom
</span>
<span>
#item.bathroom
</span>
<span>
2
</span>
</div>
<div class="desc">
#item.descrip
</div>
<div class="contact-save">
<a href="#" class="phone_number" id="favorite" onclick="Fav(this)" data-id="#item.id" >
<i class="fas fa-heart" style=" color: white;"></i>
</a>
<div class="popup" onclick="myFunction()">
<a href="tel:+928754756478" class="phone_number" onclick="call()">
</a>
</div>
<div class="popupmsg" onclick="myFunctionmsg()">
<a href="#" class="phone_number open_message" onclick="msg()">
</a>
</div>
<a href="#" class="phone_number" onclick="del(this)" data-id="#item.id">
<i class="fas fa-trash-alt" style=" color: white;"></i>
</a>
</div>
</div>
</div>
}
</div>
My Controller:
public IActionResult Rent(int PageNumber = 1)
{
var data = rdb.GetDataHouse();
var datas = rdb.GetDataHouse();
ViewBag.Data = datas.ToList().Take(6);
ViewBag.Totalpages = Math.Ceiling(data.Count()/6.0);
data = data.Skip((PageNumber - 1) * 6).Take(6).ToList();
return View(data);
}
Pass the filter data through a input submit in the form. You will need new viewModel with your data, input for post and filterList
You need something like this,
#model YourViewModel;
//Your form
<label asp-for="Input.Name"></label>
<select asp-for="Input.Name" asp-items="#(new SelectList(Model.SearchList))" class="form-control">
<option></option>
</select>
<span asp-validation-for="Input.Name" class="text-danger"></span>
<input type="submit" value="Search" class="btn btn-primary"/>
//your loop
#foreach (var item in Model.Data)
//Contoller
public IActionResult Rent(int PageNumber = 1, InputModel input)
{
var data = rdb.GetDataHouse();
var datas = rdb.GetDataHouse();
ViewBag.Data = datas.ToList().Take(6);
ViewBag.Totalpages = Math.Ceiling(data.Count()/6.0);
if(!string.InNullOrEmpty(input.Name))
{
data = data.Where(x => x.Name == input.Name).ToList();
}
data = data.Skip((PageNumber - 1) * 6).Take(6).ToList();
var viewModel = new YourViewModel
{
Data = data // data,
SearchList = your List<string>(), //for dropdown
Input = new YourInputModel(),
}
return View(viewModel);
}
//Input model
public class YourInputModel
{
public string Name { get; set; }
}
//View model
public class YourViewModel
{
public YourDataType Data{ get; set; }
public List<strings> SearchList { get; set; }
public YourInputModel Input { get; set; }
}
You also need some other things, which I hope you will handle

asp.net mvc 4 data not binding

i'm currently working on a use case where the user take a snapshot with his webcam, the snapshot is then displayed along with a form generated in javascript containing one hidden field (with the base64 code of the snapshot) and one submit button.
Problem is, the action do get called but the model is empty...I've been locked on this for multiple hours...
Datamodel :
namespace backend_OCR.Models
{
public class SnapshotModels
{
public string data_uri { get; set; }
}
}
Controller :
public ActionResult Capture()
{
ViewBag.uri = "URI_test";
return View();
}
[HttpPost]
public ActionResult Capture(SnapshotModels snapshot)
{
ViewBag.uri = snapshot.data_uri;
return View();
}
View :
#model backend_OCR.Models.SnapshotModels
#{
ViewBag.Title = "Capture";
}
<script type="text/javascript" src="~/Content/js/webcamjs.js"></script>
<div class="content-wrapper">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">Camera</div>
<div class="panel-body">
<div class="container" id="my_camera"></div>
<!-- A form for taking snaps and processing them-->
<form style="text-align: center; margin-top: 10px;">
<input style="text-align: center;" type="button" class="btn btn-success" value="Prendre capture" onclick="take_snapshot()">
</form>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">Snapshot</div>
<h2>#ViewBag.uri</h2>
<div class="panel-body">
#using (Html.BeginForm("Capture", "Camera", FormMethod.Post))
{
<div id="results" style="text-align: center;">
L'image capturée apparaitra ici...
</div>
}
</div>
<br />
</div>
</div>
Javascript :
<script language="JavaScript">
Webcam.set({
width: 400,
height: 300,
image_format: 'jpeg',
jpeg_quality: 100
});
Webcam.attach('#my_camera');
</script>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap(function (data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<div><img id="my_snap" src="' + data_uri + '"/></div>'
+ '<input type="hidden" value="' + data_uri + '">'
+ '<input id="save" class="btn btn-success" value="Crop and send" type="submit"/>';
</script>
You didn't assign any ID/Name to your '<input type="hidden" value="' + data_uri + '">'
so the binder doesn't know how to bind it to your model and its property. it should have the same name/id your c# model class uses
For any other people also searching, make sure you do not have two or more inputs with the same name or that you have added the same input (using #HtmlHelper) twice, this will confuse the binder.

Getting 500 Error on Home page when publishing ASP.Net Core Web App with class library to Azure

I've been trying to deploy my web application to Azure but I get a 500 Error on the first page. I am assuming this is because of an issue with the model that I am referencing on the first page, which is being referenced to a class library in my solution.
Here's how the project looks
I've had some issues with referencing the class library before but I have been able to remedy those issues and build both projects successfully so far. And the project runs just fine in IISExpress. But when I try to deploy it to Azure, I get a 500 Error on my Home page. Here's the code for it:
#using LNCLibrary.Models.HomeViewModel
#model HomeViewModel
#{
ViewData["Title"] = "Home Page";
}
#inject SignInManager<ApplicationUser> SignInManager
#inject UserManager<ApplicationUser> UserManager
<!--
Au<!--
Author: W3layouts
Author URL: http://w3layouts.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
-->
<!DOCTYPE HTML>
<html>
<head>
<title>New Shop a E-Commerce Online Shopping Category Flat Bootstrap Responsive Website Template | Home :: w3layouts</title>
<!--css-->
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" />
<link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
<link href="css/font-awesome.css" rel="stylesheet">
<!--css-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="New Shop Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template,
Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<script src="js/jquery.min.js"></script>
<link href='//fonts.googleapis.com/css?family=Cagliostro' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Open+Sans:400,800italic,800,700italic,700,600italic,600,400italic,300italic,300' rel='stylesheet' type='text/css'>
<!--search jQuery-->
<script src="js/main.js"></script>
<!--search jQuery-->
<script src="js/responsiveslides.min.js"></script>
<script>
$(function () {
$("#slider").responsiveSlides({
auto: true,
nav: true,
speed: 500,
namespace: "callbacks",
pager: true,
});
});
</script>
<!--mycart-->
<script type="text/javascript" src="js/bootstrap-3.1.1.min.js"></script>
<!-- cart -->
<script src="js/simpleCart.min.js"></script>
<!-- cart -->
<!--start-rate-->
<script src="js/jstarbox.js"></script>
<link rel="stylesheet" href="css/jstarbox.css" type="text/css" media="screen" charset="utf-8" />
<script type="text/javascript">
jQuery(function () {
jQuery('.starbox').each(function () {
var starbox = jQuery(this);
starbox.starbox({
average: starbox.attr('data-start-value'),
changeable: starbox.hasClass('unchangeable') ? false : starbox.hasClass('clickonce') ? 'once' : true,
ghosting: starbox.hasClass('ghosting'),
autoUpdateAverage: starbox.hasClass('autoupdate'),
buttons: starbox.hasClass('smooth') ? false : starbox.attr('data-button-count') || 5,
stars: starbox.attr('data-star-count') || 5
}).bind('starbox-value-changed', function (event, value) {
if (starbox.hasClass('random')) {
var val = Math.random();
starbox.next().text(' ' + val);
return val;
}
})
});
});
</script>
<!--//End-rate-->
</head>
<body>
<!--header-->
<div class="header">
<div class="header-top">
<div class="container">
<div class="top-left">
Help <i class="glyphicon glyphicon-phone" aria-hidden="true"></i> +0123-456-789
<a asp-controller="Admin" asp-action="Index">Administration</a>
</div>
<div class="top-right" style="padding-right:1em;">
<ul>
#await Html.PartialAsync("_LoginPartial")
</ul>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="heder-bottom">
<div class="container">
<div class="logo-nav">
<div class="logo-nav-left">
<h1>New Shop <span>Shop anywhere</span></h1>
</div>
<div class="logo-nav-left1">
<nav class="navbar navbar-default">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header nav_2">
<button type="button" class="navbar-toggle collapsed navbar-toggle1" data-toggle="collapse" data-target="#bs-megadropdown-tabs">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="bs-megadropdown-tabs">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<!-- Mega Menu -->
<li class="dropdown">
Women<b class="caret"></b>
<ul class="dropdown-menu multi-column columns-3">
<div class="row">
<div class="col-sm-3 multi-gd-img">
<ul class="multi-column-dropdown">
<li>Clothing</li>
<li>Wallets</li>
<li>Shoes</li>
<li>Watches</li>
<li> Underwear </li>
<li>Accessories</li>
</ul>
</div>
<div class="col-sm-3 multi-gd-img">
<ul class="multi-column-dropdown">
<h6>Submenu2</h6>
<li>Sunglasses</li>
<li>Wallets,Bags</li>
<li>Footwear</li>
<li>Watches</li>
<li>Accessories</li>
<li>Jewellery</li>
</ul>
</div>
<div class="col-sm-3 multi-gd-img">
<img src="images/woo.jpg" alt=" " />
</div>
<div class="col-sm-3 multi-gd-img">
<img src="images/woo1.jpg" alt=" " />
</div>
<div class="clearfix"></div>
</div>
</ul>
</li>
<li class="dropdown">
Men <b class="caret"></b>
<ul class="dropdown-menu multi-column columns-3">
<div class="row">
<div class="col-sm-3 multi-gd-img">
<ul class="multi-column-dropdown">
<li>Clothing</li>
<li>Wallets</li>
<li>Shoes</li>
<li>Watches</li>
<li> Underwear </li>
<li>Accessories</li>
</ul>
</div>
<div class="col-sm-3 multi-gd-img">
<ul class="multi-column-dropdown">
<li>Sunglasses</li>
<li>Wallets,Bags</li>
<li>Footwear</li>
<li>Watches</li>
<li>Accessories</li>
<li>Jewellery</li>
</ul>
</div>
<div class="col-sm-3 multi-gd-img">
<img src="images/woo3.jpg" alt=" " />
</div>
<div class="col-sm-3 multi-gd-img">
<img src="images/woo4.jpg" alt=" " />
</div>
<div class="clearfix"></div>
</div>
</ul>
</li>
<li>Short Codes</li>
<li>Mail Us</li>
</ul>
</div>
</nav>
</div>
#*<div class="logo-nav-right">
<ul class="cd-header-buttons">
<li><a class="cd-search-trigger" href="#cd-search"> <span></span></a></li>
</ul> cd-header-buttons
<div id="cd-search" class="cd-search">
<form action="#" method="post">
<input name="Search" type="search" placeholder="Search...">
</form>
</div>
</div>*#
#*<div class="header-right2">
<div class="cart box_1">
<a href="checkout.html">
<h3>
<div class="total">
<span class="simpleCart_total"></span> (<span id="simpleCart_quantity" class="simpleCart_quantity"></span> items)
</div>
<img src="images/bag.png" alt="" />
</h3>
</a>
<p>Empty Cart</p>
<div class="clearfix"> </div>
</div>
</div>*#
<div class="clearfix"> </div>
</div>
</div>
</div>
</div>
<!--header-->
<!--banner-->
<div class="banner-w3">
<div class="demo-1">
<div id="example1" class="core-slider core-slider__carousel example_1">
<div class="core-slider_viewport">
<div class="core-slider_list">
<div class="core-slider_item">
<img src="images/b1.jpg" class="img-responsive" alt="">
</div>
<div class="core-slider_item">
<img src="images/b2.jpg" class="img-responsive" alt="">
</div>
<div class="core-slider_item">
<img src="images/b3.jpg" class="img-responsive" alt="">
</div>
<div class="core-slider_item">
<img src="images/b4.jpg" class="img-responsive" alt="">
</div>
</div>
</div>
<div class="core-slider_nav">
<div class="core-slider_arrow core-slider_arrow__right"></div>
<div class="core-slider_arrow core-slider_arrow__left"></div>
</div>
<div class="core-slider_control-nav"></div>
</div>
</div>
<link href="css/coreSlider.css" rel="stylesheet" type="text/css">
<script src="js/coreSlider.js"></script>
<script>
$('#example1').coreSlider({
pauseOnHover: false,
interval: 3000,
controlNavEnabled: true
});
</script>
</div>
<!--banner-->
<!--content-->
<div class="content">
<!--banner-bottom-->
<div class="ban-bottom-w3l">
<div class="container">
<div class="col-md-6 ban-bottom">
<div class="ban-top">
<img src="images/p1.jpg" class="img-responsive" alt="" />
<div class="ban-text">
<h4>Men’s Clothing</h4>
</div>
<div class="ban-text2 hvr-sweep-to-top">
<h4>50% <span>Off/-</span></h4>
</div>
</div>
</div>
<div class="col-md-6 ban-bottom3">
<div class="ban-top">
<img src="images/p2.jpg" class="img-responsive" alt="" />
<div class="ban-text1">
<h4>Women's Clothing</h4>
</div>
</div>
<div class="ban-img">
<div class=" ban-bottom1">
<div class="ban-top">
<img src="images/p3.jpg" class="img-responsive" alt="" />
<div class="ban-text1">
<h4>T - Shirt</h4>
</div>
</div>
</div>
<div class="ban-bottom2">
<div class="ban-top">
<img src="images/p4.jpg" class="img-responsive" alt="" />
<div class="ban-text1">
<h4>Hand Bag</h4>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<!--banner-bottom-->
<!--new-arrivals-->
<div class="new-arrivals-w3agile">
<div class="container">
<h2 class="tittle">New Arrivals</h2>
<div class="arrivals-grids">
#foreach (var item in Model.ShopProducts)
{
<div class="col-md-3 arrival-grid simpleCart_shelfItem" style="padding-bottom:1em;"
price="#item.Price" id="#item.ID" name="#item.ProductName" profilepicture="#item.ProfilePicture">
<div class="grid-arr">
<div class="grid-arrival">
<figure>
<a href="#" class="new-gri" data-toggle="modal" data-target="#myModal1">
<div class="grid-img">
<img src="~/ProductPictures/#item.ProfilePicture" class="img-responsive" alt="">
</div>
<div class="grid-img">
<img src="~/ProductPictures/#item.ProfilePicture" class="img-responsive" alt="">
</div>
</a>
</figure>
</div>
#*<div class="ribben">
<p>NEW</p>
</div>
<div class="ribben1">
<p>SALE</p>
</div>*#
<div class="block">
<div class="starbox small ghosting"> </div>
</div>
<div class="women">
<h6>#item.ProductName</h6>
<span class="size">XL / XXL / S </span>
<p>#*<del>$100.00</del>*#<em class="item_price">$#item.Price</em></p>
Add To Cart
</div>
</div>
</div>
}
<div class="clearfix"></div>
</div>
</div>
</div>
I'm sure that it must be an issue with the model i'm using for the page because it resides in the Web app project but references a model in the class library, and so I'm thinking it's another issue with the library or reference. But the problem is I can't figure out how to debug in Azure to see what the actual issue is due to the 500 error. Here's the ViewModel, Model and Controller:
ViewModel:
using System;
using System.Collections.Generic;
using System.Text;
namespace LNCLibrary.Models.HomeViewModel
{
public class HomeViewModel
{
public ICollection<Product> ShopProducts { get; set; }
}
}
Model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace LNCLibrary.Models
{
public enum Category
{
Shirts,
Accesories,
}
public enum Gender
{
Men,
Women,
Both
}
public class Product
{
public int ID { get; set; }
[Display(Name ="Name")]
public string ProductName { get; set; }
public int Price { get; set; }
[Display(Name = "Gender")]
public Gender GenderOption { get; set; }
public int Quantity { get; set; }
public Category Category { get; set; }
[Display(Name ="Created")]
public DateTime DateCreated { get; set; }
[Display(Name = "Description")]
public string ProductDescription { get; set; }
public ICollection<Size> AvailableSizes { get; set; }
[Display(Name = "Profile Picture")]
public string ProfilePicture { get; set; }
}
}
Controller:
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
HomeViewModel HVM = new HomeViewModel();
HVM.ShopProducts = await _context.Products.ToListAsync();
return View(HVM);
}
Any ideas? I'm stumped.
After you pusblished Azure App Service with the Publish dialog box in VS, open Server Explorer (View > Server Explorer), right-click on the App Service instance and choose Attach Debugger.
In the running ASP.NET application, reproduce the error or set a breakpoint before.
The breakpoint should be hit in Visual Studio.
Like locally!
In starup.cs there is a method Configure. Enable app.UseDeveloperExceptionPage() and app.UseDatabaseErrorPage() to see errors in detail.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
//app.UseExceptionHandler("/Home/Error");
app.UseDeveloperExceptionPage(); // add this to see error
app.UseDatabaseErrorPage(); // add this to see error
}
}

on bootstrap modal dialog load get data from controller

I have two controllers, both are having view.
control#1->view#1
control#2->view#2
on controller#1->view#1 I have data displayed in tabular format. in that data table, one column is hyperlink, when i click on that I want to pop up Bootstrap modal dialog. My retirement is Modal dialog should call action method of control#2 and display view#2 in modal dialog.
view#1:
#model xxx
<table id="myTable" class="table table-bordered">
<thead>
....
</thead>
<tbody>
#foreach (xx item in Model.xxx)
{
....
<td>#Html.ActionLink(item.Value.ToString(), "Display", "Controller#2", new { para1 = item.val1, para2 = item.val2}, null)</td>
}
#Html.ActionLink() is working fine it invokes Display() method of Controller#2 and eventually displays view#2. But now the requirement is view#2 should be popup modal dialog box.
FYI: both the views are using common _Layout.cshtml file.
Please help me doing this.
I've created a complete solution for you using #Ajax.ActionLink().To use Ajax.ActionLink it's very important that you add a reference to jquery.unobtrusive-ajax.min.js.In total you should have the following references in this order:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.ajax.unobtrusive/3.2.4/jquery.unobtrusive-ajax.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var p1 = new Product { ID = 1, Description = "Product 1" };
var p2 = new Product { ID = 2, Description = "Product 2" };
return View(new List<Product> { p1, p2 });
}
public PartialViewResult GetDetails(string description)
{
return PartialView("_GetDetails", description);
}
}
_GetDetails.cshtml partial view:
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal Header</h4>
</div>
<div class="modal-body">
<h3>#Model</h3>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Main view:
#model IEnumerable<MVC_Master_Pages.Models.Product>
#{
ViewBag.Title = "Home";
Layout = null;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.ajax.unobtrusive/3.2.4/jquery.unobtrusive-ajax.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="text/javascript">
function Done() {
$('#myModal').modal('show');
}
</script>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Description</th>
<th>Details</th>
</tr>
</thead>
<tbody>
#foreach (var product in Model)
{
<tr>
<td>#product.ID</td>
<td>#product.Description</td>
<td>
#Ajax.ActionLink("Details",
"GetDetails",
new { description = product.Description },
new AjaxOptions
{
UpdateTargetId = "details",
InsertionMode = InsertionMode.Replace,
OnSuccess = "Done()"
})
</td>
</tr>
}
</tbody>
</table>
<div id="details">
</div>
Output:
The second view can't be a complete view with layout. It should be a partial view and called by ajax. Check this answer to learn how to implement it.

Return list of objects from ASP.NET MVC form

I'm developing an ASP.NET MVC 5 app with C# and .NET Framework 4.5.1.
I want to create a dynamic form to allow users insert more fields if they need more. And then, when they submit the form retrieve this data on Controller.
This is my view:
#model List<TRZF.Web.API.Models.ProductViewModel>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900' rel='stylesheet' type='text/css'>
<link href="~/css/common.css" rel="stylesheet" type="text/css" media="all" />
<link href="~/css/createBatch.css" rel="stylesheet" />
<link href="~/css/createProduct.css" rel="stylesheet" />
<link href="~/css/formStyles.css" rel="stylesheet" />
<link href="~/css/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.11.2.min.js"></script>
<script src="~/js/createProducts.js"></script>
<title>Crear</title>
</head>
<body>
<!----start-header----------->
<div class="header_bg">
<div class="wrap">
<div class="header">
<!--------start-logo------>
<div class="logo">
<img src="~/images/logo.png" alt="" /><br />
<span>Versión 1.1</span>
</div>
<!--------end-logo--------->
<!----start-nav-------->
<div class="nav">
</div>
<!-----end-nav-------->
<div class="clear"> </div>
</div>
</div>
</div>
<!------end-header------------>
<div class="slider_bg">
<div class="wrap">
<div class="da-slide" style="padding:0%">
#{
using (Html.BeginForm("Save", "MyProduct", FormMethod.Post, new { name = "eProductsFrm", id = "eProductsFrm" }))
{
<div>
<table class="productsList">
<thead>
<tr>
<td>
<h4>Producto</h4>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="group">
<input type="text"
class="productClass"
name="model[0].ProductName"
id="model[0].ProductName"
required />
#*<span class="highlight"></span>
<span class="bar"></span>
<label>Nombre del producto</label>*#
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
</td>
</tr>
</tfoot>
</table>
<table class="buttonsTable">
<tr>
<td style="text-align: left;">
<input type="button" id="addrow" value="Añadir producto" />
</td>
<td>
<input type="button" class="ibtnDel" value="Borrar último producto">
</td>
</tr>
</table>
</div>
<p><input type="button" id="btnSubmit" value="Crear producto(s)" /></p>
}
<div>
<p>#Html.ActionLink("Inicio", "Index", "Home")</p>
</div>
}
</div>
</div>
</div>
</body>
</html>
The problem is that when I do submit, on Controller's method I get a null.
This is the controller:
public class MyProductController : Controller
{
//
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Save(List<ProductViewModel> viewModel)
{
return null;
}
}
How can I do to get something on MyProductController.Save method when the user click on Submit button?
I guess you have a typo here.. it should be as below:
using (Html.BeginForm("Save", "MyProduct", FormMethod.Post, new { name = "eProductsFrm", id = "eProductsFrm" }))
{
// Your code
}
I have fixed this error with this html code:
<td>
<div class="group">
<input type="text"
class="productClass"
name="[0].ProductName"
id="[0].ProductName"
required />
#*<span class="highlight"></span>
<span class="bar"></span>
<label>Nombre del producto</label>*#
</div>
</td>
Now name and id are [0].ProductName.
More info here.
In order for MVC to bind your form data to the Action method's parameters
their names should match.
In your case:
...
name="model[0].ProductName"
Should be:
...
name="viewModel[0].ProductName"
Because this is the name of the parameter that you have provided:
public ActionResult Save(List<ProductViewModel> viewModel)
Also be careful because the indexes should not be broken, which means that they should be 0, 1, 2.. etc. without skipping a number.
The way that we read in the properties is by looking for
parameterName[index].PropertyName. The index must be zero-based and
unbroken.
You can read more in Scott Hanselman's post - here
You are not linking model properties with your Html input properly.
Wrong:
<input type="text" class="productClass" name="model[0].ProductName" id="model[0].ProductName" required />
Right:
<input type="text" class="productClass" name="#Model[0].ProductName" id="#Model[0].ProductName" required />

Categories

Resources