Passing along data from Razor Form Post to F# controller - asp.net-mvc

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 ) = ...

Related

'IndexModel' does not contain a public instance or extension definition for 'GetEnumerator'

Let me preface by saying that I am new to C# and CSHTML. I created a data entry form that is supposed to post the info submitted into a SQL DB and show the list of data in a new page. I'm stuck on the following error. Any Help would be greatly appreciated
CS1579 foreach statement cannot operate on variables of type 'IndexModel' because 'IndexModel' does not contain a public instance or extension definition for 'GetEnumerator'
#page
#model sUAS_WebApp.Pages.IndexModel
#{
ViewData["Title"] = "sUAS Request Form";
}
#if (Model.errorMessage.Length > 0)
{
<div class='alert alert-warning alert-dismissible fade show' role='alert'>
<strong>#Model.errorMessage</strong>
<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='close'></button>
</div>
}
#foreach (var data in Model)
{
<form method="POST">
<div class="container" style="border: 1px solid lightgrey;">
<div class="col-100">
<div class="row">
<div class="row">
<div class="col-50">
<label for="Date">Date</label>
<input type="text" id="Date" name="Date" class="form-control" placeholder="01-JAN-2022" value="#data.sRequest.Date" />
<div class="row">
<div class="col-50">
<label for="RD">RD#</label>
<input type="text" id="RD" name="RD" class="form-control" placeholder="AB000000" value="#data.sRequest.RD" />
</div>
<div class="col-50">
<label for="EV">EV#</label>
<input type="text" id="EV" name="EV" class="form-control" placeholder="00000" value="#data.sRequest.EV" />
</div>
</div>
</div>
</div>
<label for="Requestor">Requestor</label>
<input type="text" id="Requestor" name="Requestor" class="form-control col-95" placeholder="Name / Star" value="#data.sRequest.Requestor" />
<label for="Location">Location</label>
<input type="text" id="Location" name="Location" class="form-control col-95" placeholder="542 W. 15th Street" value="#data.sRequest.Location" />
<div class="row">
<div class="col-50">
<label for="Unit_Piloting_Drone">Unit Piloting Drone</label>
<select id="Unit_Piloting_Drone" class="form-control" name="Unit_Piloting_Drone" value="#data.sRequest.Unit_Piloting_Drone">
<option value="select1"> </option>
<option value="techlab">TechLab</option>
<option value="maiu">auditor</option>
<option value="other">Forensics</option>
</select>
</div>
<div class="col-50">
<label for="Upload">Upload</label>
<select id="Upload" class="form-control" name="Upload" value="#data.sRequest.Upload">
<option value="select2"> </option>
<option value="UpYes">Yes</option>
<option value="UpNo">No</option>
</select>
</div>
<div class="col-50">
<label for="Evidence_com_ID">ID</label>
<input type="text" id="ID" name="ID" class="form-control" placeholder="Evidence.com ID" value="#data.sRequest.ID" />
</div>
<div class="col-50">
<label for="Refused">Refused</label>
<select id="Refused" class="form-control" name="Refused" value="#data.sRequest.Refused">
<option value="select3"> </option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<label for="Call_Recieved_By"> Call Received By</label>
<input type="text" id="Call_Recieved_By" name="Call_Recieved_By" class="form-control" placeholder="Name / Star" value="#data.sRequest.Call_Recieved_By" />
<div class="col-95">
<label for="Refusal_Circumstances">Refusal Circumstances</label>
<textarea id="Refusal_Circumstances" name="Refusal_Circumstances" class="form-control" placeholder="Wind Gusts Over 30mph" style="height:200px" value="#data.sRequest.Refusal_Circumstances"></textarea>
</div>
<input type="submit" value="Submit" class="btn">
</div>
</div>
</div>
</form>
}
#if (Model.successMessage.Length > 0)
{
<div class='alert alert-warning alert-dismissible fade show' role='alert'>
<strong>#Model.successMessage</strong>
<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='close'></button>
</div>
}
<br />
<br />
<br />
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Data.SqlClient;
namespace sUAS_WebApp.Pages
{
public class IndexModel : PageModel
{
public sUASData sRequest = new sUASData();
public String errorMessage = "";
public String successMessage = "";
public void OnGet()
{
}
public void OnPost()
{
sRequest.Date = Request.Form["Date"];
sRequest.RD = Request.Form["RD"];
sRequest.EV = Request.Form["EV"];
sRequest.Requestor = Request.Form["Requestor"];
sRequest.Location = Request.Form["Location"];
sRequest.Call_Recieved_By = Request.Form["Call_Recieved_By"];
sRequest.Unit_Piloting_Drone = Request.Form["Unit_Piloting_Drone"];
sRequest.Refused = Request.Form["Refused"];
sRequest.Refusal_Circumstances = Request.Form["Refusal_Circumstances"];
sRequest.Upload = Request.Form["Upload"];
sRequest.ID = Request.Form["ID"];
if ((sRequest.Date.Length == 0 || sRequest.Requestor.Length == 0 || sRequest.Location.Length == 0 || sRequest.Call_Recieved_By.Length == 0 || sRequest.Unit_Piloting_Drone.Length == 0 || sRequest.Refused.Length == 0 || sRequest.Upload.Length == 0))
{
errorMessage = "Please fill in all required fields";
return;
}
//save the new request to the database
try
{
String connectionString = "Data Source=.\\sqlexpress;Initial Catalog=sUASDatabase;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "INSERT INTO sUAS" +
"(Date, RD, EV, Requestor, Location, Call_Recieved_By, Unit_Piloting_Drone, Refused, Refusal_Circumstances, Upload, ID) VALUES " +
"(#Date, #RD, #EV, #Requestor, #Location, #Call_Recieved_By, #Unit_Piloting_Drone, #Refused, #Refusal_Circumstances, #Upload, #ID);";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Date", sRequest.Date);
command.Parameters.AddWithValue("#RD", sRequest.RD);
command.Parameters.AddWithValue("#EV", sRequest.EV);
command.Parameters.AddWithValue("#Requestor", sRequest.Requestor);
command.Parameters.AddWithValue("#Location", sRequest.Location);
command.Parameters.AddWithValue("#Call_Recieved_By", sRequest.Call_Recieved_By);
command.Parameters.AddWithValue("#Unit_Piloting_Drone", sRequest.Unit_Piloting_Drone);
command.Parameters.AddWithValue("#Refused", sRequest.Refused);
command.Parameters.AddWithValue("#Refusal_Circumstances", sRequest.Refusal_Circumstances);
command.Parameters.AddWithValue("#Upload", sRequest.Upload);
command.Parameters.AddWithValue("#ID", sRequest.ID);
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
errorMessage = ex.Message;
return;
}
sRequest.Date = ""; sRequest.Requestor = ""; sRequest.Location = ""; sRequest.Call_Recieved_By = ""; sRequest.Unit_Piloting_Drone = ""; sRequest.Refused = ""; sRequest.Upload = "";
successMessage = "Request Successfully Entered";
Response.Redirect("/RequestData");
}
}
}
Thanks

View can not find model class that is in another project

I have two project in my solution. One of my project is a class library that I want to use as models while other one is mvc 4 web application project. Now when I send my model to my partial view from my controller my view does not render and gives the error that it could not find the class and the assembly containing the class is missing however i have added the assembly reference of my class library to the mvc project.
I need to ask that is it necessary in MVC project to have models in the same project? or I am doing something wrong
#using TransactionManagment.Entities;
#{
ViewBag.Title = "D&C | User Admin";
Layout = "~/Views/Shared/MasterPageLTE.cshtml";
}
#{
var usr = (AppUser)ViewBag.User;
var usrRights = usr.AppUserRights.AllUserPossibleRights;
}
<style>
.mytabs {
font-weight: bold;
color: cadetblue;
}
</style>
<script>
function IsSuperUser() {
if (document.getElementById('chkSuperUser').checked) {
document.getElementById('tab_user_rights').style.display = 'none';
} else {
document.getElementById('tab_user_rights').style.display = 'inline';
}
}
</script>
<div class="row">
<div class="col-md-12">
<!-- Custom Tabs -->
<div class="nav-tabs-custom">
<ul class="nav nav-tabs">
<li class="mytabs active">Users</li>
<li class="mytabs" id="tab_user_rights">User Rights</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab_1">
<div class="">
<!-- form start -->
<form role="form">
<div class="box-body">
<div class="form-group">
<label>Select</label>
<select class="form-control">
<option>New User</option>
<option>option 2</option>
<option>option 3</option>
<option>option 4</option>
<option>option 5</option>
</select>
</div>
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" id="txtFirstName" placeholder="First Name">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" id="txtLastName" placeholder="Last Name">
</div>
<div class="form-group">
<label>Designation</label>
<input type="text" class="form-control" id="txtDesignation" placeholder="Enter email">
</div>
<div class="form-group">
<label>Date of Birth</label>
<input type="date" class="form-control" id="txtDateofBirth" placeholder="Date of Birth">
</div>
<div class="form-group">
<label>Email address</label>
<input type="email" class="form-control" id="txtEmailAdd" placeholder="useremail#domain.com">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="txtPassword" placeholder="Password">
</div>
<div class="form-group">
<label>Picture</label>
<input type="file" id="txtPicture">
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="chkSuperUser" onchange="IsSuperUser();"> Super User
</label>
</div>
</div><!-- /.box-body -->
</form>
</div>
</div><!-- /.tab-pane -->
<div class="tab-pane" id="tab_2">
#foreach (var upr in usrRights)
{
foreach (var right in upr.Actions)
{
<label class="">
<div class="icheckbox_minimal-blue checked" aria-checked="true" aria-disabled="false" style="position: relative;">
<input id="#{'.'+right}" type="checkbox" class="minimal" checked="" style="position: absolute; opacity: 0;"><ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; border: 0px; opacity: 0; background: rgb(255, 255, 255);"></ins>
</div>
</label>
}
}
<h4>#{usr.UserName}</h4>
</div><!-- /.tab-pane -->
<div class="box-footer">
<button type="submit" class="btn btn-primary" id="btn_addUser">Save User</button>
</div>
</div><!-- /.tab-content -->
</div><!-- nav-tabs-custom -->
</div>
</div>
Controller
namespace TransactionManagmentWeb.Controllers
{
public class UserAdministrationController : Controller
{
//
// GET: /UserAdministration/
public ActionResult UserAdministrationHome()
{
AppUser user = new AppUser {AppUserRights = new AppUserRights()};
return PartialView(user);
}
}
}
Error
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0246: The type or namespace name 'TransactionManagment' could not be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 1:
Line 2: #using TransactionManagment.Entities;
Line 3:
Line 4:
You might need to add in your view markup
#using theothernamespace.Models

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

Not able to fire button's click in MVC 4 razor?

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.

Not set Value for RadioButton in asp.net mvc

I use asp.net mvc with ViewEngine Razor and write the Radiobuttons so in html of the page:
<form id="ProductForm" method="post" action="#Url.Action("..", "..", new { area = "..." })">
<fieldset>
<div style="float: left; width: 550px; margin-top: 5px;">
<div class="editor-label">
<label for="DescriptionId">FullDescription</label>
</div>
<div class="editor-field">
<div style=" border: 1px solid Gray;">
<input type="hidden" name="DescriptionId" id="DescriptionId"/>
<div>
<input type="radio" name="radioDescription" id="radioDescriptionNew" value="New" checked="checked" />New
<input type="radio" name="radioDescription" id="radioDescriptionExist" value="Exist" />Exist
<span id="DescriptionChooseHref" style=" visibility: hidden;">(Select)</span>
</div>
<div>
<textarea id="DescriptionText" style=" width: 530px; height: 200px; margin: 5px 0 5px 5px" placeholder="Full Description"></textarea>
</div>
</div>
</div>
</div>
...
</fieldset>
</form>
But when I run my site I see there in HTML:
<input type="radio" name="radioDescription" value checked="checked" />
<input type="radio" name="radioDescription" value />
What I do wrong? Thank's.

Resources