MVC 5 Html.ValidationSummary is not showing error - asp.net-mvc

I am manually adding the following Model Error in my controller,
ModelState.AddModelError(string.Empty, "An error occurred");
However when the view is loaded, the #Html.ValidationSummary(true) is not showing any errors.
I have also tried #Html.ValidationSummary(false).
I have read many articles on this behavior and I have tried all the suggestions with no luck.
Any suggestions are greatly appreciated!

I can see it work. See the sample here: http://dotnetfiddle.net/Jz7wQj

Beware when using custom ViewData objects.
Problem Reproduced
Model
using System.ComponentModel.DataAnnotations;
namespace BrokenValidationSummaryTest.Models
{
public class MyModel
{
[Required]
public string Whatever { get; set; }
}
}
Controller
using BrokenValidationSummaryTest.Models;
using System.Web.Mvc;
namespace BrokenValidationSummaryTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Submit(MyModel postedData)
{
return View(viewName: "Index", model: postedData);
}
}
}
View "Index"
#model BrokenValidationSummaryTest.Models.MyModel
<ul class="nav nav-tabs" id="carrier-tabs">
<li class="active">
<a data-toggle="tab" href="#search" class="tab-level-1" data-tab-name="search">Search</a>
</li>
</ul>
<div class="tab-content">
<div id="search" class="tab-pane fade in active">
#Html.Partial(partialViewName: "TabBody", model: Model, viewData: new ViewDataDictionary())
</div>
</div>
View "TabBody"
#model BrokenValidationSummaryTest.Models.MyModel
#Html.ValidationSummary(excludePropertyErrors: false)
<h2>TabBody</h2>
#using (Html.BeginForm(actionName: "Submit", controllerName: "Home", method: FormMethod.Post))
{
<div>Whatever:</div>
<div>#Html.TextBoxFor(x=>x.Whatever)</div>
<input type="submit" value="Submit">
}
Explanation
The partial view has the ValidationSummary HTML helper. We pass a custom ViewData object to the partial view. This custom ViewData object passed to the partial view does not contain the ViewState found in the view 'Index'. The HTML helper ValidationSummary does not have enough required information to render the error messages properly.
Recommendation: if using custom ViewData, populate the custom ViewData with the ViewState of the parent view.

Related

HttpException: A public action method 'ListCheckListType' was not found on controller

I checked all the solutions but still doesnt work.I got a partial view page in layout page and When ı run only partial page it works but when ı run another page with layout it doesnt work.
I hope you can help me
Here is my Model :
public CheckListType CheckListType { get; set; }
public IEnumerable<SelectListItem> CheckListTypeList1 { get; set; }
And my Controller :
public ActionResult ListCheckListType()
{
ControlListTypeModel listTypeModel = new ControlListTypeModel();
List<SelectListItem> CheckListTypeList = new List<SelectListItem();
foreach (CheckListType item in checklisttypeRepository.List().ProcessResult)
{
CheckListTypeList.Add(new SelectListItem { Value = item.CheckListTypeId.ToString(), Text = item.CheckListType1 });
}
listTypeModel.CheckListTypeList1 = CheckListTypeList;
return PartialView("~/Areas/User/Views/CheckList/ListCheckListType.cshtml", listTypeModel);
}
View :
#using TodoListApp.Areas.User.Models.ViewModel
#model ControlListTypeModel
<form action="/CheckList/ListCheckListType" method="get">
<div>
CheckListType :
</div>
<div>
#Html.DropDownListFor(modelitem=>modelitem.CheckListType.CheckListTypeId,Model.CheckListTypeList1)
<button type="button" class="butt button bg-info" style="height:40px; width:98px;">Choose CheckListType</button>
</div>
Layout :
<div class="container body-content">
#Html.Action("ListCheckListType");
#RenderBody(){
}
<hr />
<footer>
<p> #DateTime.Now.Year </p>
</footer>
</div>
HttpException: A public action method 'ListCheckListType' was not found on controller
The problem occurs because it searches ListCheckListType action in wrong controller while rendered in partial view. Specifying controller name as well should fix the exception
#Html.Action("ListCheckListType", "Home"); //if action is in HomeController

How to load partial razor page into razor view

I am trying to replace my view components with razor pages but it seems that it's not possible to load a partial razor page because a model is expected to be passed yet it is my understanding that the model for a razor page should be declared in the OnGetAsync method. Here is my code...
Razor Page
#page "{id:int}"
#model _BackgroundModel
<form method="POST">
<div>Name: <input asp-for="Description" /></div>
<input type="submit" />
</form>
Razor Page Code-Behind
public class _BackgroundModel : PageModel
{
private readonly IDataClient _dataClient;
public _BackgroundModel(IDataClient dataClient)
{
_dataClient = dataClient;
}
[BindProperty]
public BackgroundDataModel Background { get; set; }
public async Task OnGetAsync(int id)
{
Background = await _dataClient.GetBackground(id);
}
public async Task OnPostAsync()
{
if (ModelState.IsValid)
{
await _dataClient.PostBackground(Background);
}
}
}
Razor View
<div class="tab-pane fade" id="client-background-tab">
<div class="row">
<div class="col-sm-12">
#await Html.PartialAsync("/Pages/Client/_Background.cshtml", new { id = 1 })
</div>
</div>
</div>
Page Load Error
InvalidOperationException: The model item passed into the
ViewDataDictionary is of type '<>f__AnonymousType0`1[System.Int32]',
but this ViewDataDictionary instance requires a model item of type
'WebApp.Pages.Client._BackgroundModel'
In this example (as per MS recommended approach in their docs) the model is set inside the OnGetAsync method which should be run when the page is requested. I have also tried #await Html.RenderPartialAsync("/Pages/Client/_Background.cshtml", new { id = 1 }) but the same error result.
How can I load the razor page into my existing view?
Microsoft confirmed this cannot be achieved and therefore razor pages cannot be used as a replacement for view components.
See the comments of their docs...
MS docs
#RickAndMSFT moderator15 hours ago
#OjM You can redirect to the page, or you can make the core view >code into a partial and call it from both.
Pages are not a replacement for partials or View Components.

Partial View not passing ViewModel correctly to controller

I have a ViewModel that looks like this:
namespace PGO.ViewModels.Players
{
public class PlayerBuyinViewModel
{
public Player Player { get; set; }
public Buyin Buyin { get; set; }
}
}
I have a view that calls this partial view and also passing in a PlayerBuyinViewModel object with Player being populated already:
#model PGO.ViewModels.Players.PlayerBuyinViewModel
#using (Html.BeginForm("Buyin", "Players"))
{
<label>#Model.Player.GetFullName()</label>
<div class="form-group col-md-12">
<label class="col-md-1 control-label">Buyin</label>
<div class="col-md-2">
#Html.TextBoxFor(m => m.Buyin.Amount)
</div>
<button class="btn btn-primary col-md-2">CONFIRM BUYIN</button>
</div>
}
When I call GetFullName() it prints out the name correctly so the Player is in the view but when I submit my form to the Controller Player in PlayerBuyinViewModel is null.
My expectation is that the same PlayerBuyinViewModel should be used when passed on to the controller with the PlayerBuyinViewModel.Player being populated as well.
Buyin.Amount is being populated as expected from the textbox.
Do I need to create a new PlayerBuyinViewModel in this partial view and repopulate it again or what might be causing this?

How can i invoke a method in a different controller including parameters using mvc 6

I'm new to developing web applications and most importantly new to mvc. I'm trying to navigate from one view to another controller action including parameters. I have the below code in my currently displaying view:
<p>
<a asp-controller="Working_set" asp-action="Create">Create new Working set</a>
</p>
#foreach (var item in Model)
{
<div class="col-sm-6 col-md-3">
<div class="thumbnail tile tile-medium">
<a asp-controller="SelectedWorking_set" asp-action="index">
<h2>
#Html.DisplayFor(modelItem => item.Name)
<input name="workingSetID" type="hidden" value="#item.Working_setID" />
</h2>
</a>
</div>
</div>
}
How can i use the Working_setID in the controller SelectedWorking_set below:
[Route("SelectedWorking_set")]
public class SelectedWorking_setController: Controller
{
private FlightmapContext _context;
public SelectedWorking_setController(FlightmapContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
[HttpPost("Index")]
public IActionResult Index([FromBody]int workingSetID)
{
//return View(_context.Project.ToList());
return View();
}
}
You need to pass input name to your controller method like below example;
<input name="workingSetID" type="hidden" value="#item.Working_setID" />
here "workingSetID" name we need to pass your controller method, Suppose your method name is "Index" then you need to write like this in your controller.
[HttpPost]
public ActionResult Index(string workingSetID)
{
//Code here
}
like this you will get "Working_setID" value in your controller method. And also you need submit button to post this value to controller.

i am getting errorin runnging my partial view

Hi i have just started MVC 4 in c#, i am having issue in rendering partial view.
i have created model for the partial view and controller action in which i am just
sending a single string for the testing reasons but when i try to render it.
it just show the following error.
[NullReferenceException: Object reference not set to an instance of an object.]
here is my controller class.
enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using my_photos.Models;
namespace my_photos.Controllers
{
public class DefaultController : Controller
{
public ActionResult Index()
{
ViewBag.Massage = "Hello Word";
return View();
}
public ActionResult About() {
ViewBag.Message = "About Page";
return View();
}
public ActionResult _RightView() {
var model = new my_photos.Models.partial(){
Winner = "Shafee Jan"
};
//ViewData["name"] = model;
return View(model);
}
}
here is model class for partial view
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace my_photos.Models
{
public class partial
{
public string Winner { get; set; }
}
}
here my partial view
#model my_photos.Models.partial
<div class="body">
<div class="content">
<div class="header">
<h1 class="nav-heading">Data</h1>
<p class="paragraph" > Winner :#Model.Winner.ToString() </p>
</div>
</div>
<div class="bottom">
<div class="header">
</div>
</div>
</div>
and here is my main layout in shared folder
#model my_photos.Models.partial
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>_Layout</title>
<link href="#Url.Content("~/Content/Style/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/Style/Side_barnav.css")" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<h3> Photos app</h3>
<p> In this app my major concerns are with the <strong>theaming</strong>!</p>
<div class="nav">
<ul class="main-menu">
<li>#Html.ActionLink("Home","Index", "Default")</li>
<li>#Html.ActionLink("About","About", "Default")</li>
<li>#Html.ActionLink("Contact","Contact", "Default")</li>
</ul>
</div>
</header>
<section>
#RenderBody()
#Html.Partial("~/Views/Shared/_partial.cshtml")
</section>
<footer>
<div class="fotter-menu">
<ul>
<li>#Html.ActionLink("Home","Index","Default")</li>
<li>#Html.ActionLink("About","About","Default")</li>
<li>#Html.ActionLink("Contact","Contact","Default")</li>
</ul>
<ul>
<li>#Html.ActionLink("Resources","Resources","Default")</li>
<li>#Html.ActionLink("Testimonial","Testimonial","Default")</li>
<li>#Html.ActionLink("Team","Team","Default")</li>
</ul>
<ul>
<li>#Html.ActionLink("Home","Index","Default")</li>
<li>#Html.ActionLink("Home","Index","Default")</li>
<li>#Html.ActionLink("Home","Index","Default")</li>
</ul>
</div>
</footer>
</body>
</html>
when ever i try to get value form the model it give me the following error.
kindly help me through this.
[NullReferenceException: Object reference not set to an instance of an object.]
This is happening because your model is null, as you can see, in actions About and Index there is no model being passed. Also partial is a keyword in C#, it will be better to have a more signifiant name.
To solve this you have to pass a model to every view that uses that layout that is expecting this model. In your case is null and an error is thrown.
public ActionResult Index()
{
ViewBag.Massage = "Hello Word";
var model = new my_photos.Models.partial(){
Winner = "Shafee Jan"
};
return View(model);
}
It is necesary to pass the model because on the below line of code the partial is rendered by default with the current view model.
#Html.Partial("_partial.cshtml", Model) #* Model is passed by default if there is no other parameter specified *#
I think what you really want to do is to call the _RightView action in your layout.
#Html.Action("_RightView", "Default")
Don't forget to modify the action to return a partial view and the passing of model in the other actions won't be necessary
public ActionResult _RightView() {
var model = new my_photos.Models.partial(){
Winner = "Shafee Jan"
};
//ViewData["name"] = model;
return PartialView("_partial", model);
}
hey this is not a big problem you are giving partial class reference to both layout and partial view.
so if you are access a _RightView Action it does't thrown a error because you are passing a object to view properly but when comes it partial view you are not passing object reference so just pass the model in
#Html.Partial("~/Views/Shared/_partial.cshtml",Model)
That's it

Resources