I am new to MVC, i want to create a login control and for i have write the below code in view:
#using (Html.BeginForm("LoginControl", "Login"))
{
<div style="float: left; line-height: 36px;">
#Html.ValidationSummary()
<div style="float: left; margin-right: 20px;">
UserName :
</div>
<div style="float: right;">#Html.TextBoxFor(o => o.login.UserName)
</div>
<br />
<div style="float: left; margin-right: 20px;">
Password :
</div>
<div style="float: right;">#Html.TextBoxFor(o => o.login.UserPassword)</div>
<br />
<div style="float: left; margin-right: 20px;">
</div>
<input type="button" value="Login" id="Login" title="Login" />
</div>
}
in controller my code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication2.Controllers
{
public class LoginController : Controller
{
//
// GET: /Default1/
public ActionResult Index()
{
return View();
}
public ActionResult LoginControl(String UserName, String UserPassword)
{
string result = "";
if (UserName == "ram" && UserPassword == "ram123")
{
result = "1";
}
if (result == "1")
{
return View("LoginControl");
}
else
{
ModelState.AddModelError("", "Invalid username or password");
return View("Index");
}
}
}
}
I am not able to get why it is working, please help me.
ok first of all change the input type of button to submit:
<input type="button" value="Login" id="Login" title="Login" />
Now Change the View Code as below:
#using (Html.BeginForm("LoginControl", "Login"))
{
<div style="float: left; line-height: 36px;">
#Html.ValidationSummary()
<div style="float: left; margin-right: 20px;">
UserName :
</div>
<div style="float: right;">#Html.TextBox("UserName")
</div>
<br />
<div style="float: left; margin-right: 20px;">
Password :
</div>
<div style="float: right;">#Html.TextBox("UserPassword")
</div>
<br />
<div style="float: left; margin-right: 20px;">
</div>
<input type="submit" value="Login" id="Login" title="Login" />
</div>
}
Hope this will help you.
Related
I have to create a book appraisal market where students can enter their book's data (title, ISBN, version, price). If the data is entered correctly, display data in another tab called 'View Appraisals'. Now, I have made this tab and everything works fine, but I have to add one more feature that would display the View Appraisals tab on all pages' tab, in the tab bar, once the user entered the correct data.
I will be adding all my code to create the program.
Model:
namespace Lab4_Students4CheapTexts.Models
{
public class Textbooks
{
// declaring data members and getter/setter
[Required]
[StringLength(100)]
public string title { get; set; }
public int ISBN { get; set; }
public int version { get; set; }
[Required]
public int price { get; set; }
// no parameter constructor
public Textbooks()
{
}
// full parameter constructor
public Textbooks(string title, int ISBN, int version, int price)
{
this.title = title;
this.ISBN = ISBN;
this.version = version;
this.price = price;
}
public override string ToString()
{
return "Your textbook: " + this.title + ", version: " + this.version + " was appraised at: " + this.price;
}
}
}
Controller:
public class HomeController : Controller
{
List<Textbooks> textbooksList = new List<Textbooks>();
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult Appraise()
{
return View();
}
[HttpPost]
public IActionResult Appraise(Textbooks textbooks)
{
if (ModelState.IsValid)
{
ViewData["Message"] = "Your textbook: " +
textbooks.title +
", Version: " +
textbooks.version +
" was priced at: " +
textbooks.price;
return View("view_appraisals", textbooks);
}
else
{
return View("Bad");
}
}
}
}
Views:
INDEX.CSHTML
<article id="box">
<header>
<h1>Students4CheapTexts</h1>
<img src="~/Images/logo.png"
alt="Logo"
height="50"
width="50" />
</header>
<ul>
<li><a class="active" href=".~/Home/Index">Home</a></li>
<li>Appraise</li>
</ul>
<p>
index
</p>
</article>
APPRAISE.CSHTML
<ul>
<li>Home</li>
<li><a class="active" href="~/Home/Appraise">Appraise</a></li>
</ul>
<form action="~/Home/Appraise" method="POST">
<div>
<label for="title">Textbook Title:</label>
<input type="text" id="make" name="title" placeholder="" />
<br />
</div>
<div>
<label for="isbn">Textbook ISBN:</label>
<input type="text" id="isbn" name="isbn" placeholder="" />
<br />
</div>
<div>
<label for="version">Textbook Version:</label>
<input type="text" id="version" name="version" placeholder="" />
<br />
</div>
<div>
<label for="originalPrice">Original Purchase Price:</label>
<input type="text"
id="originalPrice"
name="originalPrice"
placeholder="" />
<br />
</div>
<div>
<label for="condition">Condition:</label>
<select name="condition" id="condition">
<option value="likeNew">Like New</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<br />
</div>
<input type="submit" value="Appraise" />
</form>
VIEW_APPRAISALS.CSHTML
<header>
<h1>All Entered Books List</h1>
<img src="~/Images/logo.png" alt="Logo" height="50" width="50" />
</header>
<ul>
<li>Home</li>
<li>Appraise</li>
<li><a class="active" href="~/Home/view_appraisals">View Appraisals</a></li>
</ul>
<h3> The model car could not be created because you have entered something incorrectly.</h3>
BAD.CSHTML
<header>
<h1>Incorrect input</h1>
<img src="~/Images/logo.png" alt="Logo" height="50" width="50" />
</header>
<ul>
<li>Home</li>
<li>Appraise</li>
</ul>
<h3> The model car could not be created because you have entered something incorrectly.</h3>
CSS for all my HTML pages:
/* Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
/* Provide sufficient contrast against white background */
a {
color: #0366d6;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active,
.nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
/* Sticky footer styles
-------------------------------------------------- */
html {
font-size: 14px;
}
#media (min-width: 768px) {
html {
font-size: 16px;
}
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
/* Sticky footer styles
-------------------------------------------------- */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: none;
}
html {
position: relative;
min-height: 100%;
font-family: sans-serif;
}
body {
/* Margin bottom by footer height */
margin: 60px;
text-align: center;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px; /* Vertically center the text there */
}
ul {
display: inline-block;
margin: 20px;
padding: 20px 0;
background: #aaa;
border: 1px solid #000;
}
ul li {
display: inline-block;
}
ul li a {
text-decoration: none;
color: #000;
padding: 20px 30px;
font-size: large;
font-weight: bold;
}
ul li a.active {
background: #eee;
}
p {
width: 40vw;
text-align: justify;
margin: auto;
line-height: 35px;
}
article.box {
background-color: #ddd;
}
form {
border: 1px dotted #000;
width: 60vw;
padding: 20px 0;
margin: auto;
}
form div {
margin: 20px 0;
}
form div input {
border: 1px solid #000;
}
form input[type=submit] {
padding: 10px 20px;
}
header h1 {
font-size: 40px;
}
You can perhaps put the Partial Tag Helper on each of the cshtml pages you want to include in any of your tabs.
Index.cshtml
<article id="box">
<header>
<h1>Students4CheapTexts</h1>
<img src="~/Images/logo.png"
alt="Logo"
height="50"
width="50" />
</header>
<ul>
<li><a class="active" href=".~/Home/Index">Home</a></li>
<li>Appraise</li>
</ul>
<p>
Here is stuff from indes page and below is the stuff from View_Appraisals. You can include it anywhere.
<hr />
<partial name="VIEW_APPRAISALS">
</p>
If the data is entered correctly, display data in another tab called
'View Appraisals'. Now, I have made this tab and everything works
fine, but I have to add one more feature that would display the View
Appraisals tab on all pages' tab, in the tab bar, once the user
entered the correct data.
You could try to use the _layout page to display the tab bar navigation link, code like this:
_layout.cshtml: (check the navbar)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - WebApplication1</title>
<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">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">WebApplication1</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<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-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" href="~/Home/Appraise">Appraise</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" href ="~/Home/view_appraisals">View Appraisals</a>
</li>
</ul>
</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">
© 2020 - WebApplication1 - <a asp-area="" asp-controller="Home" asp-action="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)
</body>
</html>
Then, in other views, there is no need to add navigation link, just using the layout page, code like this:
Index.cshtml:
#{
ViewData["Title"] = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<article id="box">
<p>
index Page
</p>
</article>
Code in the Appraise.cshtml page:
<h1>Appraise</h1>
#*<ul>
<li>Home</li>
<li><a class="active" href="~/Home/Appraise">Appraise</a></li>
</ul>*#
<form action="~/Home/Appraise" method="POST">
<div>
<label for="title">Textbook Title:</label>
<input type="text" id="make" name="title" placeholder="" />
<br />
</div>
<div>
<label for="isbn">Textbook ISBN:</label>
<input type="text" id="isbn" name="isbn" placeholder="" />
<br />
</div>
<div>
<label for="version">Textbook Version:</label>
<input type="text" id="version" name="version" placeholder="" />
<br />
</div>
<div>
<label for="originalPrice">Original Purchase Price:</label>
<input type="text"
id="originalPrice"
name="originalPrice"
placeholder="" />
<br />
</div>
<div>
<label for="condition">Condition:</label>
<select name="condition" id="condition">
<option value="likeNew">Like New</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<br />
</div>
<input type="submit" value="Appraise" />
</form>
Code in the view_appraisals view:
#model IEnumerable<WebApplication1.Models.Textbooks>
<table class="table">
#* list all model *#
</table>
In the controller, I will use the session to store the correct data. After submitting the correct data, store the data into session, then, get data from the session and display all the records. You could also store them into the database. (To use session in asp.net core, check Session and state management in ASP.NET Core, then configure session state and add the SessionExtensions (uses to store complex object)).
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult Appraise()
{
return View();
}
[HttpPost]
public IActionResult Appraise(Textbooks textbooks)
{
if (ModelState.IsValid)
{
ViewData["Message"] = "Your textbook: " +
textbooks.title +
", Version: " +
textbooks.version +
" was priced at: " +
textbooks.price;
//check if session exist and the the data.
if (HttpContext.Session.Get<List<Textbooks>>("textbooks") != null)
{
textbooksList = HttpContext.Session.Get<List<Textbooks>>("textbooks");
}
textbooksList.Add(textbooks);
HttpContext.Session.Set<List<Textbooks>>("textbooks", textbooksList);
// ViewData["isDisplay"] = true;
return View("view_appraisals", textbooksList);
}
else
{
return View("Bad");
}
}
public IActionResult view_appraisals()
{
if (HttpContext.Session.Get<List<Textbooks>>("textbooks") == null)
{
HttpContext.Session.Set<List<Textbooks>>("textbooks", textbooksList);
}
else
{
textbooksList = HttpContext.Session.Get<List<Textbooks>>("textbooks");
}
if (textbooksList.Count>0)
{
// ViewData["isDisplay"] = true;
return View("view_appraisals", textbooksList);
}
else
{
return View("bad");
}
}
The result like this: (if the entered data correct, it will directly redirect to the view_appraisal page)
You might want to hide the "View Appraisals" navigation link if there have no data, and, if there has records, display the "View Appraisals" navigation link. If that is the case, try to modify the navigation code (in the _layout.cshtml) as below:
#{
var isdisplay = "none"; //default value, hidden the View Appraisals link.
if (ViewData["isDisplay"] != null)
{
isdisplay = "block";
}
}
<li class="nav-item">
<a class="nav-link text-dark" style="display:#isdisplay" href ="~/Home/view_appraisals">View Appraisals</a>
</li>
Then, if you want to show the link, in the controller, set a value for "ViewData["isDisplay"]", code like this:
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult Appraise()
{
if (HttpContext.Session.Get<List<Textbooks>>("textbooks") != null)
{
ViewData["isDisplay"] = true;
}
return View();
}
[HttpPost]
public IActionResult Appraise(Textbooks textbooks)
{
if (ModelState.IsValid)
{
ViewData["Message"] = "Your textbook: " +
textbooks.title +
", Version: " +
textbooks.version +
" was priced at: " +
textbooks.price;
if (HttpContext.Session.Get<List<Textbooks>>("textbooks") != null)
{
textbooksList = HttpContext.Session.Get<List<Textbooks>>("textbooks");
}
textbooksList.Add(textbooks);
HttpContext.Session.Set<List<Textbooks>>("textbooks", textbooksList);
ViewData["isDisplay"] = true;
return View("view_appraisals", textbooksList);
}
else
{
return View("Bad");
}
}
public IActionResult view_appraisals()
{
if (HttpContext.Session.Get<List<Textbooks>>("textbooks") == null)
{
HttpContext.Session.Set<List<Textbooks>>("textbooks", textbooksList);
}
else
{
textbooksList = HttpContext.Session.Get<List<Textbooks>>("textbooks");
}
if (textbooksList.Count>0)
{
ViewData["isDisplay"] = true;
return View("view_appraisals", textbooksList);
}
else
{
return View("bad");
}
}
Then, the result like this:
Here are my codes, im using asp.net Web applications MVC
Basically just need allow admin/superuser to be able to update the rates for membership 'in those 2 textboxes names lifetime and yearlyrates and it will display in "Prices" in a non-admin view when clicked on the duration for membership renewal. Would be great if someone can help me with these codes.
This is the view that allows admin to update the prices for yearly and lifetime membership rates
#model RenewMember
#{
ViewData["Title"] = "Membership Renewal";
Layout = "~/Views/Shared/_Layout.cshtml";
string msg = ViewData["msg"] as string;
var Duration = new[]
{
new { value=1, text="1 year"},
new { value=2, text="2 years"},
new { value=3, text="3 years"},
new { value=4, text="Life-time"}
};
#section ScriptSection {
<script>
function DisplayPrice() {
var price1yearmember = 100;
var rate = 1;
var subtotal = 0;
if (selectedCurrency == "USD") {
subtotal = price1yearmember * rateUSD;
}
else if (selectedCurrency == "MYR") {
subtotal = price1yearmember * rateMYR;
}
else if (selectedCurrency == "SGD") {
subtotal = price1yearmember * rate;
}
$("#txtPrice").val(subtotal.toFixed(2));
}
</script>
}
}
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Contact Us</title>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="~/lib/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<script src="~/lib/moment/min/moment.min.js"></script>
<script src="~/lib/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js"></script>
<script type='text/javascript' src='https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&render=explicit&ver=2.0'></script>
<style>
<style > .input-group-addon {
cursor: pointer;
}
#BsDateTimePicker {
cursor: pointer;
}
</style>
<script type="text/javascript">
$(function () {
$('#BsDateTimePicker').datetimepicker({
format: 'YYYY-MM-DD'
});
});
</script>
<script src="~/lib/jquery-validation/src/core.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<meta charset="utf-8" />
<title>Contact Us</title>
<style type="text/css">
#head {
font-family: 'Times New Roman', Times, serif;
font-style: oblique;
font-size: larger;
text-align: center;
color: black;
will-change: contents;
font-weight: 900;
}
#late {
font-family: 'Times New Roman', Times, serif;
font-style: italic;
font-size: larger;
text-align: center;
color: black;
will-change: contents;
}
.field-validation-error {
font-weight: bold;
color: red;
/*background-color: yellow;*/
font-family: 'Times New Roman', Times, serif;
font-style: unset;
font-size: medium;
}
.validation-summary-errors {
border: 2px dashed red;
color: red;
/*background-color: yellow;*/
font-weight: bold;
margin: 12px;
}
</style>
</head>
<form class="form-horizontal" asp-action="RenewMember">
#if (User.IsInRole("Admin") || User.IsInRole("SuperUser"))
{
<div class="form-group">
<label input id="txtYearRate" class="control-label col-sm-3" asp-for="YearlyRate">Rates per year : </label>
<div class="col-sm-5">
<input asp-for="YearlyRate" class="form-control" />
</div>
<div class="has-error">
<span asp-validation-for="YearlyRate" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label input id="txtLifeRate" class="control-label col-sm-3" asp-for="LifeRate">Rates for Lifetime membership : </label>
<div class="col-sm-5">
<input asp-for="LifeRate" class="form-control" />
</div>
<div class="has-error">
<span asp-validation-for="LifeRate" class="text-danger"></span>
</div>
</div>
}
else
{
<div class="form-group">
<label class="control-label col-sm-3" asp-for="Email">Email : </label>
<div class="col-sm-5">
<input asp-for="Email" class="form-control" />
</div>
<div class="has-error">
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" asp-for="RenewDuration">Duration : </label>
<div class="col-sm-4">
#foreach (var freq in Duration)
{
<input type="radio" asp-for="RenewDuration" value="#freq.value" /> #freq.text
}
</div>
<div class="has-error">
<span asp-validation-for="RenewDuration" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Price: </label>
<div class="col-sm-6" style="padding-right:15px;">
<input id="txtPrice" class="form-control" value="-" readonly disabled style="background-color:#C0C0C0" />
</div>
<div class="col-sm-1" style="padding-left:0">
#{
Html.RenderPartial("_CurrencySelector");
}
</div>
</div>
}
#if (User.IsInRole("Admin") || User.IsInRole("SuperUser"))
{
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<input type="submit" class="btn btn-primary" value="Save" />
</div>
</div>
}
else
{
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<input type="submit" class="btn btn-primary" value="Renew" />
</div>
</div>
}
</form>
This is my model code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace PSS.Models
{
public class RenewMember
{
[DataType(DataType.EmailAddress)]
[Required(ErrorMessage = "Required Field")]
public string Email { get; set; }
[Range(1, 4, ErrorMessage = "Please select a Duration for renewal")]
public int RenewDuration { get; set; }
[Required(ErrorMessage = "Required Field")]
public int YearlyRate { get; set; }
[Required(ErrorMessage = "Required Field")]
public int LifeRate { get; set; }
public string Currency { get; set; }
public float CurrencyRate { get; set; }
}
}
And this will be my controller which has nothing much in it yet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PSS.Models;
using System.Security.Claims;
using System.Data;
using Microsoft.EntityFrameworkCore;
using System.Text;
using System.Threading;
using System.Net.Mail;
using System.Net;
using System.Web;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using MimeKit;
using static System.Net.Mime.MediaTypeNames;
using MailKit.Net.Smtp;
using System.Linq.Dynamic;
using Microsoft.AspNetCore.Authorization;
using System.Dynamic;
namespace PSS.Controllers
{
public class RenewMemberController : Controller
{
private AppDbContext _dbContext;
public RenewMemberController(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public IActionResult Index()
{
// DbSet<RenewMember> dbs = _dbContext.RenewMember;
//var lstType =
// dbs.ToList<RenewMember>()
// .OrderBy(p => p.TypeName)
// .Select(
// p =>
// {
// dynamic d = new ExpandoObject();
// d.value = p.MemberTypeId;
//d.text = p.TypeName;
//return d;
// }
// )
//.ToList<dynamic>();
//ViewData["currency"] = lstCurrency;
return View();
}
}
}
This is what i tried
[HttpPost]
public IActionResult UpdateRate(RenewMember rate)
{
if (ModelState.IsValid)
{
DbSet<RenewMember> dbs = _dbContext.RenewMember;
RenewMember nrate = dbs.Where(m => m.Id == rate.Id).FirstOrDefault();
if (rate != null)
{
nrate.YearlyRate = rate.YearlyRate;
nrate.LifeRate = rate.LifeRate;
string msg = "";
if (_dbContext.SaveChanges() == 1)
msg = String.Format("Rates info updated!");
TempData["Msg"] = msg;
}
else
{
TempData["Msg"] = "Rate not found!";
return RedirectToAction("Index");
}
}
else
{
TempData["Msg"] = "Invalid information entered";
}
return RedirectToAction("Index");
}
When i click "Save" button it shows localhost page not found, it redirects me to "http://localhost:49228/renewmember/RenewMember" which does not exist. My page is suppose to be http://localhost:49228/renewmember/Index. However my database is still not updated.
Just to answer the question, you have it pointing to RenewMember
<form class="form-horizontal" asp-action="RenewMember">
You might consider different controller methods:
<form class="form-horizontal" asp-action="UpdateAdminMember">
and a separate view with different controller method:
<form class="form-horizontal" asp-action="SaveNewMember">
OR use some helpers
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
{
As for your example for admin (and another partial view for the non-admin view)
#using (Html.BeginForm("UpdateAdminMember", "RenewMember", FormMethod.Post))
{
#Html.LabelFor(m => m.YearlyRate)
#Html.TextBoxFor(m => m.YearlyRate)
...
}
How is it possible to pass along data using Razor in a F# MVC5 web application.
For instance, in the view below when the PostEmail form is posting how can I pass along the value of the newEmail input as well as some fields from ViewData?
And for the DeleteEmail form, how can I get the selected option value from the emails select?
My View: (Settings.cshtml)
<div style="width: 100%;">
<h2 id="title" style="margin: 0 auto;">#ViewBag.PageTitle</h2> <br> <br>
<div style="width: 60%; margin: 0 auto;">
<div style="float: left; clear: none; width: 45%;">
<span>EMAILS</span> <br>
#using (Html.BeginForm("DeleteEmail", "QualityScore", FormMethod.Post))
{
<select id="emails" size="10" style="width: 100%; max-width: 100%">
#foreach (string email in ViewBag.EmailList)
{
<option value="#email">#email</option>
}
</select>
<input type="submit" id=" email_delete" value="Delete" />
}
#using (Html.BeginForm("PostEmail", "QualityScore", FormMethod.Post))
{
<input id="newEmail" />
<input type="submit" id="email_create" value="Create" />
}
</div>
</div>
</div>
My Controller: (QualityScoreController.fs)
type QualityScoreController(queries : DataQueries) =
inherit Controller()
new () = new QualityScoreController(DataQueries())
member this.Settings(token) =
let db = DataConnection.GetDataContext()
let user = queries.FindUserByToken(token, db)
this.ViewData.Add("PageTitle", "Your QualityScore Report Settings")
this.ViewData.Add("EmailList", queries.FindUsersReportEmails(user.Id, db))
this.ViewData.Add("KeywordList", queries.FindUsersReportBrands(user.Id, db))
this.ViewData.Add("UserID", user.Id)
this.View()
member this.PostEmail() =
... //need to use information sent from the form
member this.DeleteEmail() =
... //need to use information sent from the form
MY SOLUTION
My View: (Settings.cshtml)
<div style="width: 100%;">
<h2 id="title" style="margin: 0 auto;">#ViewBag.PageTitle</h2> <br> <br>
<div style="width: 60%; margin: 0 auto;">
<div style="float: left; clear: none; width: 45%;">
<span>EMAILS</span> <br>
#using (Html.BeginForm("DeleteEmail", "QualityScore", FormMethod.Post))
{
<select name="emails" size="10" style="width: 100%; max-width: 100%">
#foreach (string email in ViewBag.EmailList)
{
<option value="#email">#email</option>
}
</select>
<input type="submit" id=" email_delete" value="Delete" />
<input name="userid" none value="#ViewBag.UserID" />
}
#using (Html.BeginForm("PostEmail", "QualityScore", FormMethod.Post))
{
<input name="newEmail" />
<input type="submit" id="email_create" value="Create" />
<input name="userid" none value="#ViewBag.UserID" />
}
</div>
</div>
</div>
My Controller: (QualityScoreController.fs)
type QualityScoreController(queries : DataQueries) =
inherit Controller()
new () = new QualityScoreController(DataQueries())
member this.Settings(token) =
let db = DataConnection.GetDataContext()
let user = queries.FindUserByToken(token, db)
this.ViewData.Add("PageTitle", "Your QualityScore Report Settings")
this.ViewData.Add("EmailList", queries.FindUsersReportEmails(user.Id, db))
this.ViewData.Add("KeywordList", queries.FindUsersReportBrands(user.Id, db))
this.ViewData.Add("UserID", user.Id)
this.View()
member this.PostEmail(newEmail: string, userid : int) =
...
member this.DeleteEmail(emails : string, userid : int) =
...
ASP.NET MVC will automagically bind form values to namesake parameters of your actions:
member this.PostEmail( newEmail: string ) = ...
I manually placed the following code in the _Layout.cshtml
#model AssignmentTrialMVC.Models.Search
<div id="loginStrip">
#if (Request.IsAuthenticated)
{
<span style="border-right: 1px solid white; padding-right: 5px;">
<strong>#Html.Encode(User.Identity.Name)</strong>
#Html.ActionLink("Sign Out", "Logout", "User")
</span>
}
else
{
<span style="border-right: 1px solid white; padding-right: 5px;">
#Html.ActionLink("Register", "Register", "User")
</span>
<span style="padding-left: 5px;">
#Html.ActionLink("Sign In", "Login", "User")
</span>
}
</div>
<div id="searchCell">
#using (Html.BeginForm())
{
#Html.TextBoxFor(u => u.brand)
<input id="searchSubmitButton" type="submit" value="SEARCH" />
}
</div>
I can view the controls in the screen but I can not click on the controls, but using tab I can focus the controls.
Please help me with this.
I'm new to MVC. I got pictures stored in my table called "Resim".
I want to see the pictures when I call the associated record from the view.I will use its id to call it. Here is my code of the controller:
public ActionResult Details(int id = 0)
{
SozlukEntities db = new SozlukEntities();
KelimeTuru kelime = db.KelimeTuru.Find(id);
if (kelime == null)
{
return HttpNotFound();
}
return View(kelime);
}
Here is my code of the view:
#model SozlukRG.Models.KelimeTuru
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<fieldset>
<p>Move the mouse pointer over this paragraph.</p>
<legend>KelimeTuru</legend>
<div class="div1" style="display: table; background-color: #b0c4de;">
<div class="div1" style="display: table-row;">
<div class="div1" style="display: table-cell; padding: 10px;">
#Html.DisplayNameFor(model => model.KelimeId)
</div>
<div class="div1" style="display: table-cell; padding: 10px;">
#Html.DisplayNameFor(model => model.VideoId)
</div>
<div class="div1" style="display: table-cell; padding: 10px;">
#Html.DisplayNameFor(model => model.ResimId)
</div>
<div class="div1" style="display: table-cell; padding: 10px;">
#Html.DisplayNameFor(model => model.Anlam)
</div>
</div>
<div class="div1" style="display: table-row;">
<div class="div1" style="display: table-cell; padding: 10px;">
#Html.DisplayFor(model => model.KelimeId)
<div class="div1" style="display: table-cell; padding: 10px;">
<video width="320" height="240" controls>
<source src="/Videos/b.mp4" type="video/mp4">
</video>
</div>
<div class="div1" style="display: table-cell; padding: 10px;">
#*The Image will be inserted here, PLEASE HELP ME WITH THIS :) *#
</div>
<div class="div1" style="display: table-cell; padding: 10px;">
#Html.DisplayFor(model => model.Anlam)
</div>
</div>
</div>
</fieldset>
<p>
#Html.ActionLink("Back to List", "Index")
</p>
Resim is the name of the table and Adi is the VARBINARY(MAX) column with the picture. I want to see the picture in the view.
Please Help..Thanks in advance...
You could create a dedicated Image controller which handles displaying images:
public class ImageController : Controller
{
public ActionResult Show(int id)
{
SozlukEntities db = new SozlukEntities();
KelimeTuru kelime = db.KelimeTuru.Find(id);
byte[] data = kelime.Aidi;
return File(data, "image/jpg");
}
}
I skipped error checking for clarity. Also, the return type might be different than "image/jpg".