asp.net mvc client side validation not working? - c#

For some reason my client side validation does not seem to be working:
Here is my html:
#using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
<hr />
#Html.ValidationSummary(true)
<hr />
<p>
<label>Select Client_ID: </label>
<span class="field">
<select name="clientId" id="clientId">
#foreach (var item in Model.ClientId)
{
<option value="#item">#item</option>
}
</select>
</span>
</p>
<p>
<label>#Html.LabelFor(model => model.UserModel.name)</label>
<span class="field">
#Html.EditorFor(model => model.UserModel.name)
</span>
#Html.ValidationMessageFor(model => model.UserModel.name)
</p>
<p>
<label>#Html.LabelFor(model => model.UserModel.password)</label>
<span class="field">
#*<input name="password" id="password" type="password" />*#
#Html.EditorFor(model => model.UserModel.password)
</span>
#Html.ValidationMessageFor(model => model.UserModel.password)
</p>
<p>
<label>#Html.LabelFor(model => model.UserModel.email)</label>
<span class="field">
#*<input name="email" id="email" type="email" />*#
#Html.EditorFor(model => model.UserModel.email)
</span>
#Html.ValidationMessageFor(model => model.UserModel.email)
</p>
<p>
<label>Select: </label>
<span class="field">
<select name="accessLevel" id="accessLevel">
<option value="3">Company</option>
<option value="5">End-User</option>
</select>
</span>
</p>
<input type="submit" value="Submit" />
Here is my model:
public class CreateUserModel
{
[Required]
[Display(Name = "Client_ID")]
public string clientId { get; set; }
[Required(ErrorMessage = "A name is required")]
[MaxLength(20), MinLength(2, ErrorMessage = "Name must be 2 character or more")]
[Display(Name = "Name")]
public string name { get; set; }
[Display(Name = "Email Address")]
[Required(ErrorMessage = "Email is Required")]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}" +
#"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
#".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
ErrorMessage = "Email is not valid")]
public string email { get; set; }
[Required]
[MaxLength(20), MinLength(6, ErrorMessage = "Password Must be 6 or more chataters long")]
[Display(Name = "Password")]
public string password { get; set; }
[Required]
public int accessLevel { get; set; }
}
and I do have client side enabled in the webconfig:
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
{EDIT} added rendered html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page - My ASP.NET Application</title>
<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<script src="/Scripts/jquery.validate.js"></script>
<div class="jumbotron">
<h1>Add Users to the website</h1>
</div>
<form action="/Home/Create" method="post"> <hr />
<hr />
<p>
<label for="UserModel_name">Name</label>
<span class="field">
<input type="text" name="name" />
</span>
<span class="field-validation-valid" data-valmsg-for="UserModel.name" data-valmsg-replace="true"></span>
</p>
<p>
<label for="UserModel_password">Password</label>
<span class="field">
<input name="password" id="password" type="password" />
</span>
<span class="field-validation-valid" data-valmsg-for="UserModel.password" data-valmsg-replace="true"></span>
</p>
<p>
<label for="UserModel_email">Email Address</label>
<span class="field">
<input name="email" id="email" type="email" />
</span>
<span class="field-validation-valid" data-valmsg-for="UserModel.email" data-valmsg-replace="true"></span>
</p>
<p>
<label>Select: </label>
<span class="field">
<select name="accessLevel" id="accessLevel">
<option value="3">Company</option>
<option value="5">End-User</option>
</select>
</span>
</p>
<input type="submit" value="Submit" />
</form>
<hr />
<footer>
<p>© 2014 - My ASP.NET Application</p>
</footer>
</div>
<script src="/Scripts/jquery-2.1.0.js"></script>
<script src="/Scripts/bootstrap.js"></script>

For some reason the Html helpers does not have generated validation attributes in the inputs (data-val="true" and the others), check that. Besides to check the order in which the javascript libraries are loaded:
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.validation.js"></script>
<script src="~/Scripts/jquery.validation.unobtrusive.js"></script>

Your problem is likely that you have jQuery at the bottom of your file, but you are putting jquery.validate at the top. jQuery has to come before jQuery.validate. I would suggest always putting jQuery in your header, not in the body, and it should be the first thing after modernizr.
Also, you do know that jQuery 2.x does not work with IE8 ore earlier, right?

It seems that your jquery.validate.js is in wrong position. It must be after main jquery ref.
For MVC 5, it should be as following:
_Layout.cshtml: (bottom of page)
<body>
...
...
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/jqueryval") <!-- *required for client side validation! -->
#RenderSection("scripts", required: false)
</body>
where ~/bundles/jqueryval is defined in BundleConfig.cs: RegisterBundles() method:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));

Use:
#Html.EditorFor
Instead of:
<input>
And of course you need the jquery.validate.* scripts

TRY THIS: Your validation is failing because you have hard-coded this JQuery link version at the bottom of your page, which likely has been updated to a newer version in your Scripts folder:
<script src="/Scripts/jquery-2.1.0.js"></script>
All you need to do is go to "Scripts", see if there is a "jquery-2.1.0.js" file or you updated JQuery to a newer version. Type in the newer version file name, if found, and retest. It should work now. As of this June 2017 we are on JQuery version 3.1.1
This happened to me and I was pulling my hair out till I realized I had updated JQuery and saw it removed the old version. I bet that's your issue. In case you are not doing this, I recommend you not follow the View Page templates that stick validation scripts in View Pages and instead create a simple usercontrol or masterpage or layout view page and stuff your JQuery links in there so they are shared universally by all project pages. The browser will naturally cache these pages the first time, so even if they aren't used on other pages they are not loaded again.

Not sure if this is being loaded dynamically (e.g loading a partial view with Ajax). If so then you need to parse the html with the validator on the success e.g.
Use something like...
$.validator.unobtrusive.parse(".target");
E.g.
function loadAPartialView(endPoint) {
$.ajax({
url: endPoint,
type: 'GET',
cache: false,
success: function (result) {
$('.target').html(result);
$('.target').show();
// IMPORTANT. Next line is required to get the client side validation to run.
$.validator.unobtrusive.parse(".target");
$(".loadingMessage").hide();
},
error: function (result) {
// Error message...
$(".loadingMessage").hide();
}
});
};

Related

ASP.NET Core HTML Helper is not setting Default Value for Date

I have a form where I want the date to default to today's date.
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<input asp-for="ThrDate" class="form-control" value="#DateTime.Now"
type="date" asp-format="{0:yyyy-MM-dd HH:mm}" />
<span asp-validation-for="ThrDate" class="text-danger"></span>
</div>
My research would suggest that this would work, but the value is not actually passing through. Oh, and I still want the date picker to work.
Thanks!
You can try the following code:
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<input asp-for="ThrDate" class="form-control" id="date_info" type="date" asp-format="{0:yyyy-MM-dd}" />
<span asp-validation-for="ThrDate" class="text-danger"></span>
</div>
#section Scripts{
<script>
$(document).ready(function () {
var time = new Date();
var day = ("0" + time.getDate()).slice(-2);
var month = ("0" + (time.getMonth() + 1)).slice(-2);
var today = time.getFullYear() + "-" + (month) + "-" + (day);
$('#date_info').val(today);
})
</script>
}
Result:
And if you want use datetimepicker,you can use following code:
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<div class="input-group date" id="datetimepicker1" data-target-input="nearest">
<input class="form-control datetimepicker-input" asp-for="ThrDate" type="text" data-target="#datetimepicker1" />
<div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
#section Scripts{
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.1/js/tempusdominus-bootstrap-4.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.1/css/tempusdominus-bootstrap-4.min.css" />
<script>
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY HH:mm',
defaultDate: new Date(),
});
</script>
}
Result:
And another post gives us the answer:
Set default input value Datetime.Now on create view MVC ASP.NET Core 2?
but it's in the comments, so I will detail here.
In the controller, in the GET, set the value of the model item, such like:
PostThr postThr = new PostThr { ThrDate = DateTime.Now };
return view(model);
once you do this, the value assigned in the controller passes to the view. No modification to the view is necessary.
Side note: I seem to now have trouble with the formatting of the value, but that's rich world problems, or another question.
Shout out to Stephen Muecke!

Using DatePicker with .NET

I have created a very simple DatePicker using .NET Core. Here is my model:
public class MemberViewModel
{
public string Name { get; set; }
[DisplayFormat(DataFormatString = #"{0:dd\/MM\/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DOB { get; set; }
}
Here is my View:
#model DatePicker.Models.MemberViewModel
#{
ViewData["Title"] = "MemberView";
}
<h2>MemberView</h2>
<h4>MemberViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="MemberView">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DOB" class="control-label"></label>
#Html.TextBox("datepicker")
#*<input asp-for="DOB" class="form-control" />
<span asp-validation-for="DOB" class="text-danger"></span>*#
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Here is my Layout:
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Restrict date range</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker({ minDate: -20, maxDate: "+1M +10D", dateFormat: "dd/mm/yy" });
});
</script>
The DatePicker does nothing when I click on the textbox (in all browsers). The strange thing is; if I copy and paste the HTML generated into a HTML file and then double click on the HTML file, then the DatePicker works as expected. What is the problem?
Update
Please see the HTML generated below:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Restrict date range</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker({ minDate: -20, maxDate: "+1M +10D", dateFormat: "dd/mm/yy" });
});
</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MemberView - DatePicker Hotla</title>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">DatePicker</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
</nav>
<div class="container body-content">
<h2>MemberView</h2>
<h4>MemberViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form action="/Home/MemberView" method="post">
<div class="form-group">
<label class="control-label" for="Name">Name</label>
<input class="form-control" type="text" id="Name" name="Name" value="" />
<span class="text-danger field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label class="control-label" for="DOB">DOB1</label>
<input id="datepicker" name="datepicker" type="text" value="" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8AZxPMp7tE9EgVGFaTl7fvF-ALxvEVCrHkYj_isQTt5HUG2iu3EPMhNjR_6OlI2xtybr9grj4e4c3eFwe5jY-8r5YWeWIdtSNkc5IsvYnt9JYc5ftpPSzAqzINzih1yg85DFHJLEkWRZ2EjvupuQQ5E" /></form>
</div>
</div>
<div>
Back to List
</div>
<hr />
<footer>
<p>© 2018 - DatePicker</p>
</footer>
</div>
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/site.js?v=4q1jwFhaPaZgr8WAUSrux6hAuh0XDg9kPS3xIVq36I0"></script>
<script src="/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</body>
</html>
If I comment out the following line, then it works as expected:
<script src="/lib/jquery/dist/jquery.js"></script>
You are including jQuery twice. The second jQuery inclusion overwrites your $ variable, removing the jQuery ui plugins you loaded beforehand.
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
and
<script src="/lib/jquery/dist/jquery.js"></script>
jQuery plugins work by extending the $ variable. You second inclusion of jQuery destroys the plugins previously loaded.

hidden fields in migrating recaptcha to v2

The original code
#Html.Hidden("hf-register-publickey", SettingsHelper.CaptaPublicKey, new { id = "hf-register-publickey" })
<div class="editor-field">
<script src="#string.Format("{0}/recaptcha/api/challenge?k={1}", SettingsHelper.CaptaHost, SettingsHelper.CaptaPublicKey)" type="text/javascript"></script>
<div id="captcha_contain"></div>
<noscript>
<iframe src="#string.Format("{0}/recaptcha/api/noscript?k={1}", SettingsHelper.CaptaHost, SettingsHelper.CaptaPublicKey)"
height="300" width="500" frameborder="0"></iframe>
<br />
<textarea id="recaptcha_challenge_field" name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" id="recaptcha_response_field" name="recaptcha_response_field" value="manual_challenge"></input>
</noscript>
</div>
My question is on the first line. Do I still need the hidden fields with v2? I can't find any docs that address this.

The webpage cannot be found after submit my info

I have view which name is thanks and I want to show this view after click submit , but its encounter with error like this:The webpage cannot be found
Here is my code:
public class HomeController : Controller
{
public ViewResult Index()
{
int hour = DateTime.Now.Hour;
ViewBag.greeting = hour < 12 ? "Good Morning" : "Good Afternoon";
return View ("MyView");
}
[HttpGet]
public ViewResult RsvpForm()
{
return View("RsvpForm");
}
[HttpPost]
public ViewResult RsvpForm(GuestRespons GuestRespons)
{
Repository.AddResponse(GuestRespons);
return View("Thanks", GuestRespons);
}
}
and this is my view :
#{Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>
Thanks
</title>
</head>
<body>
<p>
<h1>
thank you,#Model.Name!
</h1>
#if (Model.WillAttend== true)
{
#:it's great that you are comming.we will see you soon.
}
else
{
#:Sorry to hear that, but Thanks for letting us to know.
}
</p>
<p >
click <a asp-action="ListResponses">here</a> to see who is coming.
</p>
</body>
</html>
And this one is my button which should show thanks view:
#model FuturGoals_partyinvites_.Models.GuestRespons
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RsvpForm</title>
</head>
<body>
<form asp-action="RcvpForm" method="post">
<p>
<label asp-for="Name">Your Name:</label>
<input asp-for="Name" />
</p>
<p>
<label asp-for="Email">Your Email:</label>
<input asp-for="Email" />
</p>
<p>
<label asp-for="phone">Your Phone:</label>
<input asp-for="phone" />
</p>
<p>
<label>Will you come?</label>
<select asp="WillAttend">
<option value="">Choose an option</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</p>
<button type="submit">Submit RSVP</button>
</form>
</body>
</html>
well I don't know how get exception in mvc , I think problem should be with this line:
<button type="submit">Submit RSVP</button>
Thanks in advance.
Your form action attribute value should be a valid url in your app. If you are using the form tag helper, you need to make sure you are passing the valid HttpPost action method name you want to submit to, as the asp-action attribute value.
In your case, your http post action method name is RsvpForm, But in your form you had RcvpForm which is not a valid action method. So fix your form tag helper to use the correct action method and now it should work.
<form asp-action="RsvpForm" method="post">
<!-- Your existing form elements goes here-->
</form>
Do it something like:
<p>
<label asp-for="Name">Your Name:</label>
<input asp-for="Name" />
</p>
<p>
<label asp-for="Email">Your Email:</label>
<input asp-for="Email" />
</p>
<p>
<label asp-for="phone">Your Phone:</label>
<input asp-for="phone" />
</p>
<p>
<label>Will you come?</label>
<select asp="WillAttend">
<option value="">Choose an option</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</p>
<button type="Button" id="submitme" data-url="#Url.Action("RsvpForm","Home")">Submit RSVP</button>
Ajax form like:
$("#submitme").on("click", function () {
var url = $(this).data('url');
$.ajax({
type: 'post',//this can be change to get or post
url: url,
success: function (response) {
if (response != null && response.success) {
Alert("Success");
window.location.href = "/Home/ActionNameHere"; //You can redirect any action name here....
} else {
// DoSomethingElse()
Alert("something wrong");
}
}
});
});

Partial View returning null model

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);
}

Categories

Resources