I try to show/hide a tinymce with radobutton. Like yes/no. So there are two radio buttons. yes - will show the tiny mce and no will hide the tinymce.
I have this:
showing tiny mce:
<div class="form-group">
#Html.Label(Resources.Entity.Product.PdfMessage, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name, id = "tinyMCE" } })
#Html.ValidationMessageFor(model => mailModel.PdfMessage)
#*#Html.TextArea("MailProductHandlers_message", mailModel.Message, new { #class = "form-control", #rows = 15 })*#
</div>
</div>
these are my radio buttons:
<div class="form-group">
#Html.Label(Resources.Entity.Product.GeneratePDF, new {#class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.Label(Resources.Entity.Product.GeneratePDFYes) #Html.RadioButtonFor(model => model.IsChecked, "Yes", new { #checked = true, id = "radioButton" })
#Html.Label(Resources.Entity.Product.GeneratePDFNo) #Html.RadioButtonFor(model => model.IsChecked, "No", new { #checked = true, id = "radioButton2" })
</div>
</div>
and this is my javascript:
<script>
$(document).ready(function () {
$("input[Id='radioButton']").click(function () {
if ($(this).is(':checked')) {
$('#tiny-mce').show();
}
else {
$('#tiny-mce').hide();
}
});
});
</script>
if I do this: $('#mceu_61').hide(); it hides the editor. but after I press on yes, it shows the editor. but if I then press No it doesnt hide anymore. And I have this:
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", #id = "mceu_61", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
Your missing an #symbol for the id attribute:
Modify your script as well like this:
***EDIT some thing seems off about the radio buttons only one should be checked and they should have the same name **
you can use the # to denote and ID in Jquery by the way instead off looking it up by attribute
EDIT I changed a few things around, I don't think you need two individual ids I grouped them with a class, you should be able to check the on change event from that class instead of checking on both ids
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", #id = "tinyMCE", #data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
#Html.RadioButtonFor(model => model.IsChecked, "Yes", new { #checked = true, #class = "pdfchecker" })
// only one should be checked
#Html.RadioButtonFor(model => model.IsChecked, "No", new { #checked = false, #class = "pdfchecker" })
<script>
// this is short hand for document ready
$(function () {
//# is to denote an ID, . is to denote a class in jQuery the change function is hit when a radio button is change check the name to make sure they are apart of the same grouping
$(".pdfchecker").change(function () {
if ($(this).is(':checked')) {
$('#tiny-mce').show();
}
else {
$('#tiny-mce').hide();
}
});
</script>
Related
I'm new to MVC and still figuring out how everything works. Currently, I am trying to call a method that is in my controller from my view but I'm not sure the best way to go about this. Here is my SalesOrdersController method that I want to run.
public ActionResult revertToPending(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SalesOrder salesOrder = db.SalesOrders.Find(id);
if (salesOrder == null)
{
return HttpNotFound();
}
ViewBag.statusList = new List<Object>
{
new {value = SOStatus.Pending, text = "Pending" },
new {value = SOStatus.Released, text = "Released" },
new {value = SOStatus.Released, text = "Shipped" },
new {value = SOStatus.BackOrdered, text = "Back Ordered" },
new {value = SOStatus.Cancelled, text = "Cancelled" },
};
return View(salesOrder);
}
Here is my view
<div class="form-group">
#Html.LabelFor(model => model.SalesOrderStatus, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SalesOrderStatus, new SelectList(ViewBag.statusList, "value", "text"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SalesOrderStatus, "", new { #class = "text-danger" })
#Html.ActionLink("Revert to Pending", "revertToPending", "SalesOrder")
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BillingStatus, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EnumDropDownListFor(model => model.BillingStatus, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BillingStatus, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Details, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Details, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Details, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn" />
</div>
</div>
And I want that to run when the user presses a button from the view.
So something like this
#Html.ActionLink("Revert to Pending", "revertToPending", "SalesOrder" )
I know that I'm doing it wrong as I don't want it to lead to the revertToPending View as it doesn't exist. But I want that controller method to run when the link is pressed.
Thanks
I am explicitly creating a dropdownlist in razor mvc view. I would like the default option to be one of the items, the value of that item should come from database
View Code
<div class="form-group">
#Html.LabelFor(model => model[i].Customer.HomeType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="SerivcesRegistrationInput col-md-10">
#Html.DropDownListFor(model => model[i].Customer.HomeType, new List<SelectListItem>
{
new SelectListItem{ Text="House", Value = "House",#(Model[i].CustomerServices.HomeType == "House" ? Selected = true : false) },
new SelectListItem{ Text="Apartment", Value = "Apartment" },
new SelectListItem{ Text="Farm", Value = "Farm" } },
"Select your home type", htmlAttributes: new { #class = "form-control" })
}
</div>
</div>
Controller Code
cs.HomeType = serviceDetails.HomeType;
sp.CustomerServices = cs;
return View("EditCustomerServices", ProviderList);
Model has the data I need but how can I set it to correct Dropdown list value. I tried using short hand if but it gives me an error
Invalid member initializer
Can I add if condition for Selected Boolean?
#{
var selected = Model.CustomerServices.HomeType == "House";
}
<div class="form-group">
#Html.LabelFor(model => model.Customer.HomeType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="SerivcesRegistrationInput col-md-10">
#Html.DropDownListFor(model => model.Customer.HomeType, new List<SelectListItem>
{
new SelectListItem{ Text="House", Value = "House", Selected = selected },
new SelectListItem{ Text="Apartment", Value = "Apartment" },
new SelectListItem{ Text="Farm", Value = "Farm" } },
"Select your home type", htmlAttributes: new { #class = "form-control" })
}
</div>
</div>
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 = "...")].
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 { }))
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).