MVC Template editors and post - asp.net-mvc

I'm at a beginner with ASP.NET MVC 4 and I have a problem. Basically I have this controller:
public ViewResult Login()
{
return View(new LoginViewModel());
}
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
if (authProvider.Authenticate(model.LoginUserName, model.LoginPassword))
{
return Redirect(Url.Action("Index", "Home"));
}
TempData["message"] = "Nome utente e/o password errati!!!";
return View();
}
return View();
}
That implements a simple login view. I created also a ViewModel:
public class LoginViewModel
{
[Required(ErrorMessage = "Il nome utente è obbligatorio")]
[UIHint("TextBoxLogin")]
public string LoginUserName { get; set; }
[Required]
public string LoginPassword { get; set; }
}
Finally I created the EditorTemplate:
#model string
<input name="#ViewData.TemplateInfo.HtmlFieldPrefix" id="#ViewData.TemplateInfo.HtmlFieldPrefix"data-validation="required" data-validation-error-msg="#ViewData["HelpMessage"]" value="#Model" />
So far so good. The problem is in the view. If I put this in the view:
#using(Html.BeginForm()) {
#Html.ValidationSummary(true)
#Html.EditorForModel()
<p><input type="submit" value="Log in" /></p>
}
It works like a charm (but it puts a lot of not wanted html into the page), in fact, when I click on the submit button it goes to the POST actionResult of the controller. If I put this:
#using (Html.BeginForm("Login","Account",FormMethod.Post))
{
<p class="username">
<label for="UserName">Nome utente</label>
#Html.EditorFor(m => m.LoginUserName, new { HelpMessage = "Il nome utente è obbligatorio!!!" });
</p>
<p class="password">
<label for="Password">Password</label>
#Html.EditorFor(m => m.LoginPassword)
</p>
<p>
<input type="submit" value="Log in" />
</p>
}
It does not go on the post actionresult but always on the Get one. I want to put this type of code (the last one) in wich I can setup exactly the html but I want that it goes on the POST Actionresult, can someone help me to understand why?
-----------------update----------------
Here is the HTML generated:
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<title>Title</title>
<meta name="robots" content="noindex,nofollow" />
<link href="/static/css/login.css" rel="stylesheet" type="text/css" />
<link href="/static/css/jquery_ui.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]><link href="/static/css/lt_ie9.css" rel="stylesheet" type="text/css" /><![endif]-->
<script src="/static/js/jquery_1_10_2.js"></script>
<script src="/static/js/jquery_ui.js"></script>
<script src="/static/js/jquery_ui_function.js"></script>
</head>
<body>
<form>
<div id="top">
<div class="wrapped">
<div id="logo">TITLE</div>
</div>
</div>
<div id="content" class="user_student">
<div class="wrapped">
<div class="login_intro">
<h2>TEST</h2>
</div>
<div class="login_input">
<p id="error_messages"></p>
<h2>THIS ONE MAKES GET REQUEST</h2>
<form action="/Account/Login" method="post"> <p class="username"><label for="UserName">Nome utente</label>
<!--<input id="UserName" name="UserName" type="text"/>-->
<input name="LoginUserName" id="LoginUserName"data-validation="required" data-validation-error-msg="Il nome utente è obbligatorio!!!" />;
</p>
<p class="password"><label for="LoginPassword">Password</label>
<input class="text-box single-line" data-val="true" data-val-required="Il campo LoginPassword è obbligatorio." id="LoginPassword" name="LoginPassword" type="text" value="" />
</p>
<p><input type="submit" value="Log in" /></p>
</form> <p class="hidden">old</p>
</div>
<div class="login_footer">
<p>FOOTER</p>
</div>
</div>
</div>
<h2>THIS ONE MAKE POST REQUEST</h2>
<form action="/Account/Login?ReturnUrl=%2f" method="post"><div class="editor-label"><label for="LoginUserName">LoginUserName</label></div>
<div class="editor-field"><input name="LoginUserName" id="LoginUserName"data-validation="required" data-validation-error-msg="" /> <span class="field-validation-valid" data-valmsg-for="LoginUserName" data-valmsg-replace="true"></span></div>
<div class="editor-label"><label for="LoginPassword">LoginPassword</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="Il campo LoginPassword è obbligatorio." id="LoginPassword" name="LoginPassword" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="LoginPassword" data-valmsg-replace="true"></span></div>
<p><input type="submit" value="Log in" /></p>
</form><script src="/static/form-validator/jquery.form-validator.min.js"></script>
<script src="/static/js/jquery_form_validator_function.js"></script>
</form>
</body>
</html>

Finally I figured out what is the problem...and of course it is the most stupid thing in the world.
In the rended code there is a open just after the body and, inside it, the form that MVC put from razor view.
Thanks for everyone for the help paricularly to #DavidG

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:

Two object in one form binding

How obtain value of hotel in Controller ? now i have only null. The nested object are not allowed because of html 5 doesn't let to be nested. I have objects in template but only object knight bring the value and I need also further written controls values. I ve tried to put the object but without formater yet, but I dont think it has meaning now.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Add knight</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" th:href="#{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" />
<script th:src="#{/webjars/jquery/3.2.1/jquery.min.js}"></script>
<script th:src="#{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
</head>
<body>
<div class="container">
<form class="form-horizontal" th:object="${knight}" th:action="#{/assignQuest}" th:method="post">
<input type="hidden" th:field="*{id}"/>
<input type="hidden" th:field="*{name}"/>
<input type="hidden" th:field="*{age}"/>
<input type="hidden" th:field="*{level}"/>
<div class="form-group">
<label class="control-label">Wykonaj zadanie</label>
<select th:field="*{quest}">
<option th:each="quest : ${notStartedQuests}"
th:value="${quest.id}"
th:text="${quest.description}">?</option>
</select>
</div>
<input type="hidden" th:field="*{name}"/>
<input type="hidden" th:field="*{id}"/>
<ul>
<label class="control-label">Zamiesszkaj w hotelu</label>
<li th:each="hotel : ${hotels}">
<input type="radio" th:field="*{id}" th:value="${hotel.id}" />
<label th:for="${hotel.name}" th:text="${hotel.name}"></label>
</li>
</ul>
<div class="row">
<button type="submit" class="btn btn-default">Wyslij rycerza</button>
</div>
</form>
</div>
</body>
</html>
QuestController:
import java.util.List;
#Controller
public class QuestController {
#Autowired
KnightService knightService;
#Autowired
QuestService questService;
#Autowired
HotelService hotelService;
#RequestMapping("/assignQuest")
public String assignQuest(#RequestParam("knightId") Integer id, Model model) {
Knight knight = knightService.getKnight(id);
List<Quest> notStartedQuests = questService.getAllNotStartedQuests();
List<Hotel> hotels = hotelService.getAllHotels();
model.addAttribute("knight", knight);
model.addAttribute("notStartedQuests", notStartedQuests);
model.addAttribute("hotels", hotels);
return "assignQuest";
}
#RequestMapping(value = "/assignQuest", method = RequestMethod.POST)
public String assignQuest(Knight knight, Hotel hotels, BindingResult result) {
System.out.println(result);
System.out.println(hotels);
knightService.updateKnight(knight);
// Quest quest = knight.getQuest();
// questService.update(quest);
return "redirect:/knights";
}
}

ASP.Net MVC Popup Message after submit button clicked

I'm new to MVC so I'm not completely sure that I have the model tied into the controller and view as it should be. I'm trying to have a message pop up after an error has occured. In this case the error occurs after the submit button has been clicked.
The view...
#if (ViewBag.Message != null)
{
<script>
$(document).ready(function () {
alert('#ViewBag.Message');
});
</script>
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Guru Dental: Request Demo</title>
<!-- CSS -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,400">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Droid+Sans">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lobster">
<link rel="stylesheet" href="~/Content/assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="~/Content/assets/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="~/Content/assets/css/animate.css">
<link rel="stylesheet" href="~/Content/assets/css/magnific-popup.css">
<link rel="stylesheet" href="~/Content/assets/flexslider/flexslider.css">
<link rel="stylesheet" href="~/Content/assets/css/form-elements.css">
<link rel="stylesheet" href="~/Content/assets/css/style.css">
<link rel="stylesheet" href="~/Content/assets/css/media-queries.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Favicon and touch icons -->
<link rel="shortcut icon" href="~/images/favicon.ico" type="image/x-icon">
<link rel="icon" href="~/images/favicon.ico" type="image/x-icon">
</head>
<body>
<!-- Top menu -->
<nav class="navbar" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#top-navbar-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<br>
<img class="logo-size" src="~/images/guru-dental-slogan.png" alt="">
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="top-navbar-1">
<ul class="nav navbar-nav navbar-right">
<li><a href='#Url.Action("Index", "Home")'><br><br>Home</a></li>
<li>
<a href='#Url.Action("Contact", "Home")'><br><br>Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Title -->
<div class="page-title-container">
<div class="container">
<div class="row">
<div class="col-sm-12 wow fadeIn">
<h1>Demo Request</h1>
</div>
</div>
</div>
</div>
<!-- Contact Us -->
<div class="contact-us-container">
<div class="container">
<div class="row">
<div class="col-sm-7 contact-form wow fadeInLeft">
#using (Html.BeginForm("DemoSubmit", "CRM", FormMethod.Post))
{
<h2>Rep Details</h2>
<div class="form-group">
<label for="contact-firstname">HSD Rep Code</label>
<input type="text" name="hsdrepcode" placeholder="Enter your HSD Rep code..." class="contact-name" id="contact-name">
</div>
<div class="form-group">
<label for="contact-lastname">Rep First Name</label>
<input type="text" name="hsfirstname" placeholder="Enter your Rep first name..." class="contact-name" id="contact-name">
</div>
<div class="form-group">
<label for="contact-lastname">Rep Last Name</label>
<input type="text" name="hslastname" placeholder="Enter your Rep last name..." class="contact-name" id="contact-name">
</div>
<h2>Doctor Details</h2>
<div class="form-group">
<label for="contact-currentlocation">Doctor's First Name</label>
<input type="text" name="firstname" placeholder="Enter your doctor's first name.." class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label for="contact-currentlocation">Doctor's Last Name</label>
<input type="text" name="lastname" placeholder="Enter your doctor's last name..." class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label for="contact-currentlocation">Doctor's Phone Number</label>
<input type="text" name="phonenumber" placeholder="Enter your doctor's phone number..." class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label for="contact-currentlocation">Doctor's E-mail</label>
<input type="text" name="emailaddress" placeholder="Enter your doctor's e-mail..." class="contact-subject" id="contact-subject">
</div>
<button type="submit" class="btn">Submit</button>
}
</div>
The controller...
public ActionResult RequestDemo()
{
return View();
}
[HttpPost]
public ActionResult DemoSubmit(LeadInfo leadInfo)
{
string salesEmail = CRMModels.GetNextSalesEmail();
ViewBag.Message = CRMModels.AddLeadToCRM(leadInfo);
if (ViewBag.Message == null)
{
EmailModels.SendEmailForLead(leadInfo, salesEmail);
return RedirectToAction("Index", "Home");
}
else
return RequestDemo();
}
}
The model...
if (hsdRepId != Guid.Empty)
{
lead.Attributes["ree_hsdrepresentative"] = new EntityReference("ree_henryscheinrepresentative", hsdRepId);
service.Create(lead);
}
else
{
message = "Invalid HSD Representative Code";
}
return message;
In the DemoSubmit function, if there is a message to display, I need to go back to the view to display it. How do I do that? I tried to do with a redirect but that just gives me a new page with none of the data that was entered in and it didn't display the message.
Thanks,
Gary
On controller once you got error you can add error message to modalState
ModelState.AddModelError("", "Invalid HSD Representative Code");
and to pop the error alert you can use html extension method to pop the message
public static HtmlString PopAlert(this HtmlHelper htmlHelper, string alertType = "danger",
string heading = "")
{
if (htmlHelper.ViewData.ModelState.IsValid)
return new HtmlString(string.Empty);
var sb = new StringBuilder();
sb.AppendFormat("<div class=\"alert alert-{0} alert-block\">", alertType);
sb.Append("<button class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>");
if (!heading.IsNullOrWhiteSpace())
{
sb.AppendFormat("<h4 class=\"alert-heading\">{0}</h4>", heading);
}
sb.Append(htmlHelper.ValidationSummary());
sb.Append("</div>");
return new HtmlString(sb.ToString());
}
On view you simply call the Html extension method like this
#Html.PopAlert()
hope this will help you :)
You have a number of problems with your code, in particular the fact you not binding any controls to you model so returning the view will always display empty controls. You should also include validation attributes on you properties to prevent posting and saving potentially bad data. Your view is also generating invalid html (lots of duplicate id attributes) and <label> tags which are not really labels (clicking on them wont set focus to the associated control because you don't associate them with a control.
Based on your view, your LeadInfo class looks something like (suggested attributes added)
public class LeadInfo
{
[Display(Name = "HSD Rep code")]
[Required(ErrorMessage = "Please enter your HSD Rep code")]
public string hsdrepcode { get; set; }
[Display(Name = "Rep first name")]
[Required(ErrorMessage = "Please enter your Rep first name")]
public string hsfirstname { get; set; }
.....
[Display(Name = "Doctor's e-mail")]
[Required(ErrorMessage = "Please enter your doctor's e-mail")]
[EmailAddress]
public string emailaddress{ get; set; }
}
You GET method should then be
public ActionResult RequestDemo()
{
LeadInfo model = new LeadInfo();
return View(model);
}
and the view should then strongly typed html helpers to bind to your properties and to display validation errors
#model LeadInfo
....
#using(Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true) // this is where you custom error message will be displayed
#Html.LabelFor(m => m.hsdrepcode) // displays the text associated with the DisplayAttribute and is associated with the following textbox
#Html.TextBoxFor(m => m.hsdrepcode, new { placeholder="Enter your HSD Rep code...", #class="contact-name"})
#Html.ValidationMessageFor(m => m.hsdrepcode)
....
<button type="submit" class="btn">Submit</button>
}
You should also include the following scripts (preferably using #Scripts.Render() and the bundling and minification features of MVC)
jquery-{version}.js
jquery.validate.js
jquery.validate.unobtrusive.js
You should also be using layouts (master pages)
The post method is then
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RequestDemo(LeadInfo model) // not sure why you would change the name of the method?
{
if(!ModelState.IsValid)
{
return View(model); // return the view to fix any validation errors
}
string errorMessage = CRMModels.AddLeadToCRM(leadInfo);
if (errorMessage == null)
{
string salesEmail = CRMModels.GetNextSalesEmail();
EmailModels.SendEmailForLead(leadInfo, salesEmail);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", errorMessage);
return View(model);
}
}
Its not clear what the error message you want to return is, but you code suggests it might be associated with the hsdrepcode property, in which case, modify the code to associate the error with a particular property
ModelState.AddModelError("hsdrepcode", errorMessage);
Side note: Most of your code is ignoring the benefits of using MVC, to the point you may as well not use it. I recommend you go the the MVC site and work through the tutorials,

Why does my partial view not working?

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"))

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