My problem is:
I have two fields, and when i call my #Html.Actionlink method it send a null value for these two parameters.
This is my page code:
<div id="new-skill" class="row">
<label for="Description">Descreva brevemente a sua habilidade:</label>
#Html.TextBoxFor(model => model.skill.Description, new { #class = "form-control" })
<label for="Name">Em qual categoria ela está?</label>
#Html.TextBoxFor(model => model.skill.Category.Name, new { #class = "form-control" })
<div class="text-center margin-top15">
#Html.ActionLink("Adicionar nova habilidade", "InsertNewSkill", new
{
professionalId = ViewBag.professionalId,
skillDescription = "Test Text",
categoryName = Model.skill.Category.Name
}, new
{
#class = ""
})
</div>
</div>
This is my InsertNewSkill method:
public ActionResult InsertNewSkill(int professionalId, string skillDescription, string categoryName)
{
initBusinessObjects();
var professional = professionalBusiness.GetById(professionalId);
var newSkill = new SkillModel { Description = skillDescription, Category = new SkillCategoryModel { Name = categoryName } };
skillBusiness.Insert(newSkill);
professional.Skills.Add(newSkill);
professionalBusiness.Update(professional);
return View();
}
What I must to do to achieve this (send the textbox values)?
Have you tried adding the controllerName to your actionLink?
#Html.ActionLink("Adicionar nova habilidade", "InsertNewSkill","CONTROLLER_NAME", new
{
professionalId = ViewBag.professionalId,
skillDescription = "Test Text",
categoryName = Model.skill.Category.Name
}, new
{
#class = ""
})
Without using jQuery / javascript, you should use a form to get those values back to the server.
#{using(Html.BeginForm("InsertNewSkill", "ControllerName", FormMethod.Get)){
<div id="new-skill" class="row">
<label for="Description">Descreva brevemente a sua habilidade:</label>
#Html.TextBoxFor(model => model.skill.Description, new { #class = "form-control" })
<label for="Name">Em qual categoria ela está?</label>
#Html.TextBoxFor(model => model.skill.Category.Name, new { #class = "form-control" })
#Html.Hidden("professionalId", ViewBag.professionalId)
<div class="text-center margin-top15">
<input type="submit" value="Adicionar nova habilidade"/>
}}
With that said, typically you should POST these values back to the server and then redirect to a new ActionMethod (Thus, the acronym PRG for Post, Redirect, Get).
Related
I have a form where a Chat is registered in the database, everything works fine, the problem is the ViewBag, since this takes the message to Javascript in the view so that it can place a validation. When the user registers, a success message should appear, but by the ViewBag it appears as an error, in the database if the user's data is displayed, so the only problem would be the ViewBag.
Also, when I re-run again, the modal with the message success appears just fine.
Controller
//Charlas
public ActionResult CrearCharla()
{
List<ClsSede> listaSede = new List<ClsSede>();
ClsSede Sede1 = new ClsSede();
Sede1.sede_Text = "LIMA - SAN BORJA";
Sede1.sede_Value = "LIMA - SAN BORJA";
ClsSede Sede2 = new ClsSede();
Sede2.sede_Text = "LIMA - LOS OLIVOS";
Sede2.sede_Value = "LIMA - LOS OLIVOS";
ClsSede Sede3 = new ClsSede();
Sede3.sede_Text = "LIMA - CHORRILLOS";
Sede3.sede_Value = "LIMA - CHORRILLOS";
listaSede.Add(Sede1);
listaSede.Add(Sede2);
listaSede.Add(Sede3);
ViewBag.Sedes = new SelectList(listaSede, "sede_Text", "sede_Value");
return View(new ClsCharla());
}
[HttpPost]
public ActionResult CrearCharla(ClsCharla charla)
{
List<ClsSede> listaSede = new List<ClsSede>();
ClsSede Sede1 = new ClsSede();
Sede1.sede_Text = "LIMA - SAN BORJA";
Sede1.sede_Value = "LIMA - SAN BORJA";
ClsSede Sede2 = new ClsSede();
Sede2.sede_Text = "LIMA - LOS OLIVOS";
Sede2.sede_Value = "LIMA - LOS OLIVOS";
ClsSede Sede3 = new ClsSede();
Sede3.sede_Text = "LIMA - CHORRILLOS";
Sede3.sede_Value = "LIMA - CHORRILLOS";
listaSede.Add(Sede1);
listaSede.Add(Sede2);
listaSede.Add(Sede3);
ViewBag.Sedes = new SelectList(listaSede, "sede_Text", "sede_Value", charla.sede_Charla);
//-----
string message = "";
try
{
ClsConexion con = new ClsConexion();
var Cnx = con.Conexion();
OracleCommand cmd = new OracleCommand("SIMEXA_SP_REGISTER_CHAT", Cnx);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("param_titulo", OracleDbType.Varchar2)).Value = charla.titulo_Charla.Trim();
cmd.Parameters.Add(new OracleParameter("param_descrip", OracleDbType.Varchar2)).Value = charla.descrip_Charla.Trim();
cmd.Parameters.Add(new OracleParameter("param_fecha", OracleDbType.Varchar2)).Value = charla.fecha_Charla;
cmd.Parameters.Add(new OracleParameter("param_hora", OracleDbType.Varchar2)).Value = charla.hora_Charla;
cmd.Parameters.Add(new OracleParameter("param_lugar", OracleDbType.Varchar2)).Value = charla.lugar_Charla.Trim();
cmd.Parameters.Add(new OracleParameter("param_sede", OracleDbType.Varchar2)).Value = charla.sede_Charla;
cmd.Parameters.Add(new OracleParameter("param_requisito", OracleDbType.Varchar2)).Value = charla.requisito_Charla.Trim();
Cnx.Open();
OracleTransaction tx = Cnx.BeginTransaction();
cmd.ExecuteNonQuery();
tx.Commit();
Cnx.Close();
cmd.Dispose();
Cnx.Dispose();
message = "success";
}
catch
{
message = "error";
}
finally
{
ViewBag.message = message;
}
return RedirectToAction("MostraCharlas");
}
View
#model wsCharlas.Models.ClsCharla
#{
ViewBag.Title = "Create a Chat";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create a Chat:</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<h4>Here you can place all the respective data of the chat you want to create.</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<!-- <div class="form-horizontal"> -->
<div class="form-group">
#Html.HiddenFor(model => model.ID_Charla, htmlAttributes: new { #class = "control-label" })
<div>
#Html.HiddenFor(model => model.ID_Charla, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ID_Charla, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.titulo_Charla, htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.titulo_Charla, new { htmlAttributes = new { #class = "form-control", maxlength = "40" } })
#Html.ValidationMessageFor(model => model.titulo_Charla, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.descrip_Charla, htmlAttributes: new { #class = "control-label" })
<div>
#Html.TextAreaFor(model => model.descrip_Charla, new { #id = "textArea", #class = "form-control", maxlength = "530" })
#Html.ValidationMessageFor(model => model.descrip_Charla, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.fecha_Charla, htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.fecha_Charla, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.fecha_Charla, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.hora_Charla, htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.hora_Charla, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.hora_Charla, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.lugar_Charla, htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.lugar_Charla, new { htmlAttributes = new { #class = "form-control", maxlength = "100" } })
#Html.ValidationMessageFor(model => model.lugar_Charla, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.sede_Charla, htmlAttributes: new { #class = "control-label" })
<div>
#Html.DropDownListFor(model => model.sede_Charla, (SelectList)ViewBag.Sedes, "Select a Headquarters", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.sede_Charla, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.requisito_Charla, htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.requisito_Charla, new { htmlAttributes = new { #class = "form-control", maxlength = "100" } })
#Html.ValidationMessageFor(model => model.requisito_Charla, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2">
<input type="submit" value="Create a Chat" id="id_charla" class="btn btn-success" />
</div>
</div>
<!--</div> -->
}
<div>
#Html.ActionLink("Return", "MostraCharlas", null, new { #class = "btn btn-primary" })
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<style>
#textArea{
min-height: 62px;
max-height: 135px;
}
</style>
<script>
var msg = '#ViewBag.message'
$("#id_charla").on("click", function () {
if (msg == 'success') {
Swal.fire(
msg,
'A new chat was added!',
'success'
)
} else {
Swal.fire(
msg,
'Could not register your new chat, be sure to complete the entire form, if the problem continues to communicate with the computer area!',
'error'
)
}
});
</script>
To answer your question, I will start by saying that getting null for the ViewBag in your case is actually correct, because you used RedirectToAction which will nullify all ViewBag data
The lifespan of a ViewBag is the current request, which means that once you attempt to leave the current request, it becomes null. So you need to use TempData in your own case.
TempData is a data stored just the way sessions are stored. It's lifespan last between two request. It helps the transfer of data from one controller to another or from one action to another. You use TempData in a bit different way from the way View data or ViewBag is used.
So I will give two options for you.
First
Use TempData and ViewBag
In the Post action change the finally line to
finally
{
TempData["message"] = message;
}
Then in the Get action you are redirecting to, because you used RedirectToAction, get the TempData and pass it to view bag
var message = TempData ["message"];
If(message != null)
ViewBag.message = message;
Note the if statement is needed to handle initial get requests, that is not setting the value of the ViewBag when the TempData is not set
Second
Use only TempData
finally
{
TempData["message"] = message;
}
Whichever you decide to use, is accessed the same way you assigned it,
TempData["message"] //for TempData
ViewBag.message //for ViewBag
I'm trying to get the create function to have the user selected values entered into the database. When the create button is pushed, no error is thrown but, the data is not populated. I'm pretty sure my frequency fields are causing the issue but have been unable to come with a solution.
There are two different types of frequencies a user can select depending upon their "Notification Name" selection. One selection has 3 separate fields for a numerical value, time frame (week, month etc.), and a before/after selection. The other simply states instantaneous as a static text field. Regardless of which option is chosen the frequency data should be populated into one cell within the database which is then separated using piping where necessary. I'm still pretty new to C# MVC so any help is greatly appreciated.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,notificationType1,recipientTypeId,frequency")] NotificationType notificationType)
{
if (ModelState.IsValid)
{
db.NotificationType.Add(notificationType);
db.SaveChanges();
return RedirectToAction("Create");
}
ViewBag.recipientTypeId = new SelectList(db.RecipientType, "Id", "recipientRole", notificationType.recipientTypeId);
return View(notificationType);
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.notificationType1, "Notification Name", htmlAttributes: new { #class = "control-label col-md-2 helper-format" })
<div class="col-md-10" id="type_selection">
#Html.DropDownList("notificationType1", new List<SelectListItem> {
new SelectListItem { Text = "Make a Selection", Value="" },
new SelectListItem { Text = "Incomplete Documents", Value= "Incomplete Documents" },
new SelectListItem { Text = "All Documents Complete", Value = "All Documents Complete" },
new SelectListItem { Text = "Documents Requiring Action", Value = "Documents Requiring Action" }
}, new { #class = "helper-format", #id = "value_select", style = "font-family: 'Roboto', Sans Serif;" })
#Html.ValidationMessageFor(model => model.notificationType1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="frequency_group">
#Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-sm-3" id="frequency_group">
#Html.TextBoxFor(model => model.frequency, new { #class = "textbox-width", #placeholder = "42" })
#Html.DropDownList("frequency", new List<SelectListItem>
{
new SelectListItem { Text = "Day(s)", Value= "| Day"},
new SelectListItem { Text = "Week(s)", Value= "| Week"},
new SelectListItem { Text = "Month(s)", Value= "| Month"}
})
#Html.DropDownList("frequency", new List<SelectListItem>
{
new SelectListItem { Text = "Before", Value= "| Before"},
new SelectListItem { Text = "After", Value= "| After"}
})
</div>
<p class="col-sm-2" id="psdatetext">The Beginning</p>
</div>
<div class="form-group" id="freq_instant">
#Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="instant_text">
<p>Instantaneous</p></div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.recipientTypeId, "Notification For", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("recipientTypeId", new List<SelectListItem>
{
new SelectListItem { Text = "Me", Value= "Me"},
new SelectListItem { Text = "Account Manager", Value="Account Manager" },
new SelectListItem { Text = "Candidate", Value= "Candidate"},
new SelectListItem { Text = "Recruiter", Value="Recruiter" },
new SelectListItem { Text = "Manager", Value= "Manager"}
})
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<div id="hovercreate">
<button type="submit" value="CREATE" class="btn btn-primary" id="createbtn">CREATE</button>
</div>
</div>
</div>
</div>
}
JS for frequency options
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function () {
$('#frequency_group').hide()
$('#freq_instant').hide()
$('#value_select').change(function () {
var selection = $('#value_select').val();
$('#frequency_group').hide();
switch (selection) {
case 'Incomplete Documents':
$('#frequency_group').show();
break;
case 'All Documents Complete':
$('#frequency_group').show();
break;
}
});
$('#value_select').on('change', function () {
if (this.value == 'Documents Requiring Action') {
$("#freq_instant").show();
}
else {
$("#freq_instant").hide();
}
});
});
Have you placed a break-point on the method? And if so, is it triggering?
If not, try this...
From what I remember, all Controllers has a default parameter of ID which is set in the RouteConfig.cs file (App_Start/RouteConfig.cs).
There's a couple of ways to go from there.
1. Give the controller the ID parameter (e.g. (int ID))
2. Set the route value via the Route attribute
To do this you need to -
A. Add the following at the top of your RouteConfig.cs / RegisterRoutes method.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//...
}
B. Add
[ValidateAntiForgeryToken]
[Route(#"Create/")]
public ActionResult Create([Bind(Include = ...
{
I would also suggest putting a break-point at the beginning of the method to see if its hitting it.
http://www.tutorialsteacher.com/mvc/routing-in-mvc
https://msdn.microsoft.com/en-us/library/system.web.mvc.routecollectionattributeroutingextensions.mapmvcattributeroutes%28v=vs.118%29.aspx
Is the Id key manually assigned? If not (for example, if it's an IDENTITY field), you shouldn't be binding it - remove Id from [Bind(Include = "...")].
I have feedback form with two fields : project_name and lastName of partner. The first fiels is correct(project_name) but instead lastName of second field I want there firstName+lastName+email, how to do it? At the moment there is only lastname, but I can have multiply lastnames for different partners. Below is sample of code how I create this form.
In my create method of feedbackController:
ViewBag.project_id = new SelectList(db.Projects.Where(p => p.project_id == project_id), "project_id", "name");
ViewBag.Id = new SelectList(db.Users_projects.Where(p => p.project_id == project_id && p.project_role == "partner").Select(up => new { up.AspNetUsers.FirstName,up.AspNetUsers.LastName, up.AspNetUsers.Id }), "Id", "LastName");
Here is my view how render this form:
<div class="form-horizontal">
<h4></h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.project_id, "Project: ", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("project_id", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.project_id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Id, " For partner : ", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Id", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
ViewBag.Id =db.Users_projects
.Where(p => p.project_id == project_id &&p.project_role == "partner")
.Select(up =>
new SelectListItem {
// You may append User email also here
Text= up.AspNetUsers.FirstName +" "+up.AspNetUsers.LastName,
Value = up.AspNetUsers.Id.ToString() })
.ToList();
You can make your code more readable/maintainable by not using dynamic stuff like ViewBag and switch to a strongly typed viewmodel to pass the data between your action method and view
public class AssignProjectOwnerShipVm
{
public int SelectedPartner {set;get;}
public int SelectedProject {set;get;}
public List<SelectListItem> Projects {set;get;}
public List<SelectListItem> Partners {set;get;}
}
and in your GET action
pubilc ActionResult AssignProject()
{
var vm = new AssignProjectOwnerShipVm();
vm.Projects = db.Projects.Select(s=>new SelectListItem
{
Value = s.ProjectId.ToString(),
Text = s.ProjectName
}).ToList();
vm.Partners=db.Users_projects
.Where(p => p.project_id == project_id &&p.project_role == "partner")
.Select(up =>
new SelectListItem {
// You may append User email also here
Text= up.AspNetUsers.FirstName +" "+up.AspNetUsers.LastName,
Value = up.AspNetUsers.Id.ToString() })
.ToList();
return View(vm);
}
And your view
#model AssignProjectOwnerShipVm
#using(Html.BeginForm())
{
#Html.DrowpDownListFor(s=>s.SelectedProject,Model.Projects,"Select one")
#Html.DrowpDownListFor(s=>s.SelectedPartner,Model.Partners,"Select one")
<input type="submit" />
}
And your HttpPost
[HttpPost]
public ActionResult AssignProjecct(AssignProjectOWnerShipVm model)
{
// check for model.SelectedParter and model.SelectedProject
// to do :Save and redirect
}
We've got a page which currently contains a four or five partial views, but is something that could grow. At the moment, there's two POST actions, for two entirely different database functions.
If we try doing the create function on another, the redirect then results in an "Object reference not set to an instance of an object." error, which is then relating to the other POST partial view.
Is there a way to stop this? Essentially, it seems to me that the post for one partial view is trying to interact with the other. Any ideas?
Thanks
Bulletins Controller for Creating:
[HttpPost]
public ActionResult CreateMain(BulletinsViewModel viewModel)
{
if (ModelState.IsValid)
{
BulletinsContext.tblBulletins.Add(new tblBulletin
{
ID = viewModel.BulletinID,
BulletinDisplayDate = viewModel.BulletinDisplayDate,
BulletinFilename = viewModel.MainBulletinName,
IsSixthForm = viewModel.IsSixthForm
});
//For loop to delete bulletins
//If bulletin folder has more than 10 files in
//Delete the oldest file, itererate till only 10 remain
{
DirectoryInfo dir = new DirectoryInfo(#"D:\Inetpub\WWWroot\intranet\Dashboard\Dashboard\Files\Bulletins");
List<FileInfo> filePaths = dir.GetFiles().OrderByDescending(p => p.CreationTime).ToList();
for (int index = filePaths.Count() - 1; index > 9; index--)
{
var fileNames = filePaths[index].Name;
//Delete from directory
filePaths[index].Delete();
//Remove from collection to restart the loop
filePaths.RemoveAt(index);
}
}
//Save changes to database
BulletinsContext.SaveChanges();
//Return to main bulletins index page
return RedirectToAction("~/Home/Index");
}
return View(viewModel);
}
Bulletins Create View:
#model Dashboard.Viewmodels.BulletinsViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.BulletinDisplayDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BulletinDisplayDate, new { htmlAttributes = new { #class = "form-control", #id = "datepicker-basic", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.BulletinDisplayDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MainBulletinName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
#Html.EditorFor(model => model.MainBulletinName, new { htmlAttributes = new { #class = "form-control", #Value = "Select File...", #readonly="readonly" } })
<span class="input-group-addon" href="javascript:;" onclick="moxman.browse({ fields: 'MainBulletinName', extensions: 'pdf', path: 'D:/Inetpub/WWWroot/intranet/Dashboard/Dashboard/Files/Bulletins' });" style="cursor: pointer;"><i class="fa fa-upload"></i></span>
#Html.ValidationMessageFor(model => model.MainBulletinName, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
<script type="text/javascript" src="~/Scripts/tinymce/plugins/moxiemanager/js/moxman.loader.min.js"></script>
Printer Credits Create Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PrinterCredits(PrinterCreditsViewModel viewModel)
{
if (ModelState.IsValid)
{
//Send the email if credits are added..
//Create a bunch of variables for the email
//Create the email body etc
var fromAddress = "";
string toName = Request.Form["Username"].ToUpper();
string AmountOfCredits = Request.Form["AmountAdded"];
string Plural = "";
string Title = "";
string AddedByWho = User.Identity.Name.Split('\\')[1];
System.DateTime AddedWhen = DateTime.Now;
if (AmountOfCredits == "1")
{
Plural = " printer credit has ";
Title = "Printer Credit Added!";
}
else
{
Plural = " printer credits have ";
Title = "Printer Credits Added!";
}
var toEmail = toName + "";
var subject = AmountOfCredits + Plural + "been added to your account, " + toName;
string body = "";
//Create an SMTP client for sending an email
var smtp = new SmtpClient
{
Host = "",
Port = 25,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = true,
};
//Populate the SMTP client and encode the body for the HTML
using (var message = new MailMessage(fromAddress, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true,
BodyEncoding = System.Text.Encoding.UTF8
})
//Try to send the email. If sent, insert data.
//Redirect back to original page
//Take current printer credit from and update with fund + cost
try
{
//Link the viewmodel and the database together
PartialViewContext.tblPrinterCredits.Add(new tblPrinterCredit
{
Username = viewModel.Username,
AmountAdded = viewModel.AmountAdded,
AddedBy = AddedByWho,
AddedWhen = viewModel.AddedWhen,
Money = viewModel.AmountAdded * 0.02
});
Nullable<double> cost = viewModel.AmountAdded * 0.02;
//Update the printer credit fund and insert into tblOption
tblOption fund = (
from n in PartialViewContext.tblOptions
where n.ID == 1
select n).First();
fund.PrinterCreditFund = fund.PrinterCreditFund + cost;
PartialViewContext.SaveChanges();
message.CC.Add("");
smtp.Send(message);
Response.Redirect("~/Home/Index");
}
//If it fails, go chicken oriental (only a redirect, will eventually become a crazy message)
catch
{
smtp.Send(message);
Response.Redirect("~/Home/Index");
}
}
return View(viewModel);
Printer Credits View:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="panel">
<div class="panel-heading">
<span class="panel-icon">
<i class="fa fa-print"></i>
</span>
Add Printer Credits - #Costings
</div>
<div class="panel-body">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-3">User:</label>
<div class="col-xs-8">
#Html.EditorFor(model => model.Username, new { htmlAttributes = new { #class = "form-control", #id = "Username", #name = "Username", #maxlength = "6" } })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Amount:</label>
<div class="col-xs-8">
#Html.EditorFor(model => model.AmountAdded, new { htmlAttributes = new { #class = "form-control", #id = "AmountAdded", #onkeyup = "Update()", #Value = 0 } })
#Html.ValidationMessageFor(model => model.AmountAdded, "", new { #class = "text-danger", #type="number" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Cost:</label>
<div class="col-xs-8">
#Html.EditorFor(model => model.TotalCost, new { htmlAttributes = new { #class = "form-control", #id = "TotalCost", #readonly = "readonly", #Value = "0" } })
#Html.ValidationMessageFor(model => model.TotalCost, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<input type="submit" value="Add Printer Credits" class="btn btn-primary btn-gradient dark btn-block" />
#Html.EditorFor(model => model.AddedBy, new { htmlAttributes = new { #class = "form-control", #Value = User.Identity.Name.Split('\\')[1], #Style = "display: none;" } })
#Html.ValidationMessageFor(model => model.AddedBy, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
}
<script type="text/javascript">
$(document).ready(
function () {
Update();
$('#AmountAdded, #TotalCost')
.keyup(function () {
Update();
})
}
);
function Update() {
var cost = 2
var one = $('#AmountAdded'),
two = $('#TotalCost');
two.val(parseInt(one.val()) * cost / 100);
}
</script>
<script type="text/javascript">
document.getElementById('Username').focus()
</script>
Just figured out that I need to tell the form which action and controller to use, despite the fact two different controllers are running the views. But anyway, an example is:
#using (Html.BeginForm("CreateMain", "Bulletins", FormMethod.Post, new { }))
I have a controller which gives a SelectList to a View which then renders multiple DropDownLists for a SelectList. I now want the DropDownLists to have different Values to be selected by Default. Is there any way of doing this?
Edit: Oh and of course the values I want to be defaults are available from my Model e.g. Model.Dj1_Id etc.
Controller:
[HttpGet]
public ActionResult EditPartyInfo(int ID)
{
Party prty = db.Partys.Find(ID);
ViewBag.People = new SelectList(db.People, "Id", "Name");
return View(prty);
}
View:
#model Musa.Models.Party
#using (Html.BeginForm("EditPartyInfo", "Events", FormMethod.Post))
{
#Html.AntiForgeryToken()
<!-- Some text input fields -->
<div class="form-group">
<label for="Dj1_Id">Dj 1</label>
<div class="form-inline">
#Html.DropDownList("Dj1_Id", ViewBag.People as SelectList, String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<div class="form-group">
<label for="Dj2_Id">Dj 2</label>
<div class="form-inline">
#Html.DropDownList("Dj2_Id", ViewBag.People as SelectList, String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<div class="form-group">
<label for="Dj3_Id">Dj 3</label>
<div class="form-inline">
#Html.DropDownList("Dj3_Id", ViewBag.People as SelectList, String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<input type="submit" class="btn btn-primary" value="Los geht's" />
}
I Actually ended up doing:
Controller:
[HttpGet]
public ActionResult EditPartyInfo(int ID)
{
Party prty = db.Partys.Find(ID);
ViewBag.People = db.People;
return View(prty);
}
View:
/*...*/
#Html.DropDownList("Dj1_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj1_Id), String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
/*...*/
#Html.DropDownList("Dj2_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj2_Id), String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
/*...*/
#Html.DropDownList("Dj3_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj3_Id), String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
Please try;
instead of
ViewBag.People as SelectList
this;
new SelectList(ViewBag.People, "Id", "Name", "Id value to select")
as second parameter of Html.DropDownLists
SelectList has a constructor where you can pass in the selected object, so:
new SelectList(db.People, "Id", "Name", db.People.FirstOrDefault(x => x.Id == party.Dj1_Id)
I personally prefer using IEnumerable<SelectListItem> like so:
ViewBag.People = db.People.Select(x => new SelectListItem { Text = x.Name, Value = x.Id, Selected = x.Id == party.Dj1_Id);
Either way should work.