Why does my partial view not working? - asp.net-mvc

I created a partial view and I use this partial to another view that it inherit from a _layout m code is true and doesn't have a bug, but when I click on submit it shows this message : (The resource cannot be found). I can't trace this error . please help me . thanks
This is my news.Cshtml:
#model MPortal.Models.WebSite_OpinionDB
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Body{
#Html.Partial("CreateOpinion")
#Html.Action("CreateOpinion", "User")
}
And this is my _Layout.cshtml :
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
<link href="~/Theme/css/bootstrap.css" rel="stylesheet">
<link href="~/Content/CssFramework.css" rel="stylesheet" />
#RenderSection("CSS", required: false)
</head>
<body>
#RenderSection("Body", required: false)
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/modernizr-2.5.3.js"></script>
<script src="~/Theme/js/bootstrap.js"></script>
#RenderSection("scripts", required: false)
</body>
</html>
And this is my Partialview :(CreateOpinion.cshtml)
#model MPortal.Models.WebSite_OpinionDB
#section Body{
<div class="" style="float: right; width: 75%">
#Html.Raw(Session["Right"])
#using (Html.BeginForm())
{
<div class="rateit" style="float: right; width: 25%">
<input type="text" maxlength="100" value="name" class="form-control" name="Values" id="NameFamily" />
<br />
<input type="text" maxlength="100" value="email" class="form-control" name="Values" id="Email" />
<br />
#Html.TextAreaFor(x => x.OpinionText, new { #class = "form-control", #placeholder = "opinion" })
<br />
<button class="btn btn-primary" type="submit">submit</button>
</div>
}
<div class="" style="width: 20%; height: 625px; border: 1px solid black; float: left">
#Html.Raw(Session["Left"])
</div>
</div>
<div class="" style="float: right; width: 75%">
#if (ViewData["Success"] != null)
{
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
#(ViewData["Success"] != null ? ViewData["Success"].ToString() : "")
</div>
}
#if (ViewData["UnSuccess"] != null)
{
<div class="alert alert-danger bs-alert-old-docs">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
#(ViewData["UnSuccess"] != null ? ViewData["UnSuccess"].ToString() : "")
</div>
}
</div>
}
and this is my action of partial view :
[ChildActionOnly]
public ActionResult CreateOpinion(MPortal.Models.WebSite_OpinionDB saveop, FormCollection frm)
{
if (!string.IsNullOrEmpty(frm["Values"]))
{
int mtID = (int)MPortal_CL.Globals.GetParam("MetaDataID", 0);
MPortal.Models.WebSite_OpinionDB op = new MPortal.Models.WebSite_OpinionDB();
String[] texts = frm["Values"].Split(',');
.....
.......
}

Remove attribute [ChildActionOnly] and if this does not work please use the overloaded version
#using (Html.BeginForm("CreateOpinion","ControllerName"))

Related

Add form to layout

I need to add a login popup to the header of every page, so naturally I want to add it to the layout as a partial view.
The problem is, the layout doesnt have a pagemodel.
We do use a BasePageModel that every page inherits from, where I can add 2 strings for username/password. But how would the layout see those fields?
You can specify a model for the Layout page just as you would a standard content page:
#model BasePageModel
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
...
Then your properties are accessible via the Model property of the Layout page. The BasePageModel will also be passed to any partials that you add to the layout (unless you specify a different model for the partial), so you can also access the properties in those.
I need to add a login popup to the header of every page, so naturally
I want to add it to the layout as a partial view.
According to your description, I do a demo for that situation. But I don’t use a BasePageModel that every page inherits from.
The demo as below, hoping it can help you.
1.Add a Login page with page model, and post method
Login.cshtml.cs:
public class LoginModel : PageModel
{
[BindProperty]
public string Username { get; set; }
[BindProperty]
public string Password { get; set; }
public string Msg { get; set; }
public void OnGet()
{
}
public IActionResult OnPost(string Username, string Password)
{
//do your other things...
return Page();
}
}
Login.cshtml:
#page
#model Login.Pages.LoginModel
#{
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
</head>
<body>
<h3>Login Form</h3>
#Model.Msg
<form method="post" asp-page="Login">
<table>
<tr>
<td>Username</td>
<td><input type="text" asp-for="#Model.Username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" asp-for="#Model.Password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</form>
</body>
</html>
Add the login form in the layout. Using name attribute: change input type="text" asp-for="#Model.Username" into input type="text" name="Username"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
</li>
</ul>
</div>
<div>
<fieldset>
<div class="container">
<div class="row">
<div class="col-xs-12">
<button id="btnShowModal" type="button"
class="btn btn-sm btn-default pull-left col-lg-11 button button4">
login
</button>
<div class="modal fade" tabindex="-1" id="loginModal"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
</div>
<div class="modal-body">
<form method="post" asp-page="Login">
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>Username</td>
<td><input type="text" name="Username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="Password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2021 - Login - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#await RenderSectionAsync("Scripts", required: false)
<script type="text/javascript">
$(document).ready(function () {
$("#btnShowModal").click(function () {
$("#loginModal").modal('show');
});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
});
</script>
</body>
</html>
Results:

(MVC) I have a search bar in my shared _Layout. It works from other Views but not in the _Layout

Basically what the title says. I have a view named books in which the search bar works perfectly and gives results. This is not happening in the _Layout shared view. I've tried several scripts and stuff but to no avail. Any advice?
This is the _Layout
<!DOCTYPE html>
#model IEnumerable<GoodReads.Models.Libro>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div 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="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Nombre de aplicación", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Inicio", "Index", "Home")</li>
<li>#Html.ActionLink("Registrar Turno", "AltaTurno", "Turno")</li>
<li>#Html.ActionLink("Buscar Libros", "Books", "Libro")</li>
<li>
#using (Html.BeginForm(FormMethod.Get))
{
<div>
#Html.TextBox("parametro")
<input type="submit" id="btnSearch" value="Some text"/>
</div>
}
</li>
</ul>
</div>
</div>
</div>
<div id="Books">
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer></footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
This is the Books view
#model IEnumerable<GoodReads.Models.Libro>
#{
/**/
ViewBag.Title = "Books";
}
<head>
<link href="#Url.Content("~/Content/Style.css")" rel="stylesheet" type="text/css" />
</head>
<body>
#foreach (var item in Model)
{
<div style="margin-left: 350px; margin-top: 50px;">
<h1 class="title-font">
#item.Title
<small class="year-font">(#item.Year)</small>
</h1>
</div>
<div style="margin-left: 350px; margin-top: 10px;">
<p style="font-size: 22px;">by #item.Author</p>
</div>
<div style="margin-left: 350px; margin-top: 10px;">
<p style="font-size: 22px;">#item.ISBN</p>
</div>
}
</body>
The Controller for Books (The conection to the database is made through instead of doing it directly in the controller)
// GET: Libro
public ActionResult Index()
{
return View();
}
public ActionResult Books(string parametro)
{
List<Libro> listalibros = ADLibros.BuscarLibro(parametro);
return View(listalibros);
}
The problem is your form. You don't set its action. If you don't tell it it will use the default which is the controller that renders the page. So when your Books controller renders the page this works because the default controller will be the books controller. You need to specify the action of your get form explicitly. To see the problem use your browser developer tools to inspect the form for the books page and the other pages.
To fix (assuming your controller for books is called BooksController) change the form code in your _Layout page to this
#using (Html.BeginForm("books", "books", FormMethod.Get))
{
<div>
#Html.TextBox("parametro")
<input type="submit" id="btnSearch" value="Some text" />
</div>
}
We are using an overload of Html.BeginForm with 3 arguments. The first is the actionName, the second is the controllerName and the 3rd is the FormMethod.

How to add javascript from partial view to layout.cshtml page

I am trying to add javascript from partial view to layout.cshtml head section by calling
#RenderSection("scripts", required: false) but failing. Please view my partialview page code.
#{
Layout = null;
}
<div id="modal-login" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-dialog-buttons ui-draggable ui-resizable" title="Insert Student">
#using (Html.BeginForm("Login", "Home", FormMethod.Post, new { id = "form-login" }))
{
<div style="width:320px; height:320px; padding:0px 15px 15px 15px; border:solid 1px silver">
<div style="width:310px; height:30px; padding-bottom:0px; border:solid 0px red">
<div style="width:320px; height:30px; float:left;">
<div id="loading" style="height:15px; width:120px">
</div>
</div>
</div>
<div style="width:310px; height:30px; padding-bottom:35px; border:solid 0px red">
<div style="width:320px; height:30px; float:left;">
<input type="text" class="textbox" id="tbEmailAddress" name="tbFirstName" size="50" placeholder="First Name" />
</div>
</div>
<div style="width:310px; height:30px; padding-bottom:35px; border:solid 0px red">
<div style="width:320px; height:30px; float:left;">
<input type="text" class="textbox" id="tbPassword" typeof="password" name="tbFirstName" size="50" placeholder="First Name" />
</div>
</div>
<div style="width:320px; height:20px; padding-top:5px; padding-bottom:15px; border:solid 0px red; font-size:9px;">
<div style="width:310px; height:30px; float:left;">
<input id="btnLogin" class="submit ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="submit" value="Submit" style="border:1px solid gray; width:80px; height:25px ">
</div>
<div style="width:140px; height:30px; float:left;">
</div>
</div>
</div>
}
</div>
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#modal-login").dialog({
show: "slide",
modal: true,
autoOpen: false,
});
$("#btnLogin").click(function () {
$("#modal-login").dialog("open");
return false;
});
});
</script>
}
And below is layout.chtml head section where iam calling #RenderSection("scripts", required: false) in the second last line of code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/jquery")
#*#Scripts.Render("~/bundles/jqueryui")*#
<link href="~/Content/themes/base/jquery-ui-1.10.4.custom.css" rel="stylesheet" />
#*<script src="~/Scripts/jquery-1.10.2.js"></script>*#
<script src="~/Scripts/jquery-ui-1.10.4.custom.js"></script>
#RenderSection("scripts", required: false)
</head>
Please view my code and suggest if i missed anything? thanks.
the order #section scripts don't work in partialView, erase that and your script work.
but why you try to put the script in the head??
You call JQuery in the head the Script in the partial view works isn't necesary up in the head.
But if I understand your code you make a login form in a partial View for insert in the layout for use in entire web site?
well is more easy if you write the script directly in the head in layout, but better is create a script file with all custom script, mix this with the others scripts in one bundle and finally call this bundle in the head, with this way your site will more faster.

JQueryValidation with MVC 4 not validating on blur

I am beating my head on the wall for hours with MVC 4 and jQuery validation to validate the first first on blur. I have tried attaching the validation to the entire form AND to the individual element (first field) to no avail. If I add an alert() into the blur event it seems to fire but no validation of the required field. I have additional validations to add after the required is working but haven't gotten to them yet. I don't know that it is a problem with the MVC 4. JQueryvalidate is v1.10. I have also tried setting up the validator and then calling .valid() on the element I want validated using the .blur and still not validation that I can see.
$(function () {
$('#productionOrder').focus();
$.validator.addMethod("cMinLength", $.validator.methods.minlength,
$.format("Must contain as least {0} chars"));
$.validator.addClassRules("productionOrder", { cMnLength: 3 });
$('#myForm').validate({
onkeyup: false,
//onfocusout: false,
errorClass: 'fieldError'
//rules: {
// productionOrder: "required number",
// tc: "required",
// dn: "required"
//}
});
$("#towCount").bind("change keyup", function () {
$form.validate().element("#towCount");
});
//$('#productionOrder').validate({
// //onkeyup: false,
// onfocusout: false,
// errorClass: 'fieldError',
// rules: {
// productionOrder: {
// required: true
// }
// }
//});
});
And the .cshtml
#model FiberLine2.ViewModels.Creel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Test</title>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<style>
.fieldError {
border-color: red;
border-width: medium;
}
.input-label {
font-size: 13px;
width: 130px;
height: 30px;
display: inline-block;
}
</style>
</head>
<body>
<form id="myForm">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div>
<!-- app header -->
<label>#Resources.Strings.User: </label>
<label>#User.Identity.Name</label>
</div>
<fieldset>
<legend>#Resources.Strings.Creel #Resources.Strings.Load</legend>
<div>
<div id="errorDiv"></div>
<hr />
#Html.Label(#Resources.Strings.ProductionOrder, new { #class = "input-label lock" })
<input type="text" id="productionOrder" name="productionOrder" class="required" maxlength="4" />
<br />
<label class="input-label lock">#Resources.Strings.Tow #Resources.Strings.Count</label>
<input type="text" id="towCount" name="tc" class="required" size="5" maxlength="5" value="299" />
<br />
<label class="input-label lock">#Resources.Strings.Batch #Resources.Strings.Sequence</label>
<input type="text" id="doffNumber" name="dn" size="5" maxlength="5" value="1" />
<br />
<label class="input-label">#Resources.Strings.Creel #Resources.Strings.Position</label>
<input type="text" id="creelPosition" name="cp" size="5" maxlength="5" />
<br />
<label class="input-label">#Resources.Strings.Batch #Resources.Strings.ID</label>
<input type="text" id="creelNumber" name="cn" size="7" maxlength="7" />
<br />
<hr />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</form>
</body>
</html>
Can you try this instead?
var settngs = $.data($('#myForm')[0], 'validator').settings;
settngs.onkeyup = false;

How to display wrong username password on login form ?

I am developing the MVC application.
I have designed the login form.
when user enters the proper username and password then, it redirect to next page, but when user put wrong username or password I want to display the message on the login form, how to do it.
This is the code of method in controller...
[HttpPost]
public ActionResult LoginUser(FormCollection oFormCollection)
{
string userName = oFormCollection["username"];
string password = oFormCollection["password"];
bool IsAccountPerson = false;
var validEmployee = (from e in db.Employees
where e.UserName == userName && e.Password == password
select e).ToList();
if (validEmployee.Count() == 1)
{
foreach (var v in validEmployee)
{
oEmployee = v;
Session["LoggedEmployee"] = oEmployee;
Session["loggedEmpId"] = oEmployee.Id;
if (oEmployee.DesignationType == "Account")
{
IsAccountPerson = true;
}
else
{
IsAccountPerson = false;
}
}
if(IsAccountPerson)
return RedirectToAction("PaymentAdviceListForAccounts", "Account");
else
return RedirectToAction("Index", "PaymentAdvice");
}
else
return PartialView("Index");
}
and this is my view Code....
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="#Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
<title></title>
</head>
#using (Html.BeginForm("LoginUser","Login",FormMethod.Post))
{
#*<div style="margin:15% 20% 20% 30%; width:35%;min-height:25%;border:1px #ACACAC solid;">*#
<div class="container-fluid" style="padding-left:0px; margin-top:165px; margin-left:140px;">
<div class ="span3">
<label style="font-size:15px; color:#666666; margin-top:5px;">Username</label>
</div>
<div class ="span6">
<input type="text" id="username" name="username" style="height:20px; width:100%;" />
</div>
<div class ="span3">
<label style="font-size:15px;color:#666666; margin-top:5px; ">Password</label>
</div>
<div class ="span6">
<input type="password" id="password" name="password" style="height:20px; width:100%;"/>
</div>
<div class="span6" style="padding-left:15px;">
<input type="submit" name="submit" value="Login" class="btn btn-primary" style="margin-right:10px; height:30px; font-size:14px; width:55px;" />
<input type="button" name="Login" value="Cancel" class="btn btn-primary" style="margin-right:20px; height:30px; font-size:14px; width:55px; padding-left:5px; padding-right:5px;" />
</div>
</div>
</div>
</div>
</div>
}
</body>
</html>
create new model or use TempData.
here is the example using TempData.
http://www.devcurry.com/2012/05/what-is-aspnet-mvc-tempdata.html

Resources