I am trying to create a view where i need to two different button calling two different controller methods. but when i place and run it gives me error.
"The required anti-forgery form field "__RequestVerificationToken" is not present."
View
#model Course.ViewModels.CourseIndexVM
#{
Script.Require("ShapesBase");
Layout.Title = T("Course").ToString();
}
#using(Html.BeginForm("Index", "CourseAdmin", FormMethod.Get)) {
<fieldset class="bulk-actions">
<label for="search">#T("Search:")</label>
#Html.TextBoxFor(m => m.Search.Expression)
<button type="submit">#T("Search")</button>
#T("Clear")
</fieldset>
}
#using (Html.BeginForm("Create", "CourseAdmin", FormMethod.Post))
{
<fieldset class="bulk-actions">
<button type="submit">#T("Create")</button>
</fieldset>
}
<fieldset>
<table class="items" summary="#T("List of Courses")">
<colgroup>
<col id="Col1" />
<col id="Col2" />
<col id="Col3" />
<col id="Col4" />
<col id="Col5" />
<col id="Col6" />
</colgroup>
<thead>
<tr>
<th scope="col">#T("ID")</th>
<th scope="col">#T("Name")</th>
<th scope="col">#T("Description")</th>
</tr>
</thead>
#foreach (var item in Model.Courses) {
<tr>
<td>#item.Id</td>
<td>#item.Name</td>
<td>#item.Description</td>
<td>
<div>
#T("Edit")#T(" | ")
#T("Delete")
</div>
</td>
</tr>
}
</table>
#Display(Model.Pager)
</fieldset>
Controller
namespace CourseAdmin.Controllers
{
[Admin]
public class CourseAdminController : Controller, IUpdateModel
{
private readonly IContentDefinitionService _contentDefinitionService;
private readonly IRepository<CoursePartRecord> _coursePartRepository;
private readonly IContentManager _contentManager;
private readonly IProjectionManager _projectionManager;
private readonly INotifier _notifier;
private readonly IOrchardServices _orchardService;
private dynamic Shape { get; set; }
private readonly ISiteService _siteService;
bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
}
void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.Text);
}
public CourseAdminController(
IShapeFactory shapeFactory,
ISiteService siteService,
IContentDefinitionService contentDefinitionService,
IContentManager contentManager,
IProjectionManager projectionManager,
IRepository<CoursePartRecord> coursePartRepository,
IOrchardServices orchardService,
INotifier notifier)
{
Shape = shapeFactory;
_siteService = siteService;
_contentDefinitionService = contentDefinitionService;
_contentManager = contentManager;
_projectionManager = projectionManager;
_coursePartRepository = coursePartRepository;
_notifier = notifier;
_orchardService = orchardService;
}
public ActionResult Create()
{
var course = _orchardService.ContentManager.New("Courses");
var editor = Shape.EditorTemplate(TemplateName: "Parts/Course.Create", Model: new CourseCreateVM(), Prefix: null);
editor.Metadata.Position = "2";
dynamic model = _orchardService.ContentManager.BuildEditor(course);
model.Content.Add(editor);
// Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
return View((object)model);
}
[HttpPost, ActionName("Create")]
public ActionResult CreatePOST(CourseCreateVM courseModel)
{
var course = _orchardService.ContentManager.New("Courses");
// Cast the customer to a UserPart
var coursePart = course.As<CoursePart>();
coursePart.Name = courseModel.Name;
coursePart.Description = courseModel.Description;
_orchardService.ContentManager.Create(course);
return RedirectToAction("Index");
}
}
}
I think you need to use
#using (Html.BeginFormAntiForgeryPost(...)) { ... }
as the wrapper for your form.
Related
Can someone help me figure out the problem i'm new on JSF. I have built a Spring WebMVC App with Primefaces. This app contains a list of nodes which can be dragged into the spreadSheet (I m working with SpreadJS). Behind each node there is a model and a bean. Evey node has a name and an input type. I need to do the synchronization between the node value and its value in the spreadSheet and aim-versa. So in every changeEvent i call a remoteCommand and i pass five parameters to my managedBean. The problem is whenever i load my page and i get this error : here is my code :
#ManagedBean
#SessionScoped
public class HelloBean implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty("#{param.nodeId}")
private String nodeId;
#ManagedProperty("#{param.paramId}")
private String paramId;
#ManagedProperty("#{param.row}")
private int row;
#ManagedProperty("#{param.cel}")
private int cel;
#ManagedProperty("#{param.value}")
private String value;
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
public String getParamId() {
return paramId;
}
public void setParamId(String paramId) {
this.paramId = paramId;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getCel() {
return cel;
}
public void setCel(int cel) {
this.cel = cel;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void execCmd() {
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String nodeId = params.get("nodeId");
}
and my xhtml file look like :
<h:body>
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<h:form id="myForm">
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Test Submit Value</label>
<h:inputText name="text1" id="text1" value="#{helloBean.value}" >
</h:inputText>
</div>
</div>
<p:remoteCommand name="callRemoteMethod" actionListener="#{helloBean.execCmd()}" />
</h:form>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div name="right_frame" id="ss" style="height: 600px; width: 100%;"></div>
</div>
</div>
</div>
<h:form>
<br />
</h:form>
</h:body>
<script type="text/javascript">
var nodeId = null;
var paramId = null;
var row = null;
var cell= null;
var value = null;
var spread;
window.onload = function() {
spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
var sheet = spread.getActiveSheet();
sheet.setValue(0, 1, 123, GC.Spread.Sheets.SheetArea.viewport);
sheet.bind(GC.Spread.Sheets.Events.CellChanged , function (e, args) {
if (args.propertyName === "value") {
if(sheet.getTag(0,1) != null){
var obj = JSON.parse(sheet.getTag(0,1));
nodeId = obj.nodeId;
paramId = obj.paramId;
row = args.row;
cell = args.col;
callRemoteMethod({name: 'nodeId', value: ""}, {name: 'paramId', value: ""}, {name: 'row', value: 1}, {name: 'cel', value: 1}, {name: 'value', value: "Test"}]);
}
}
});
};
</script>
</html>
and this is the Stack Trace :
Caused by: java.lang.IllegalArgumentException: can't parse argument number: param.nodeId
at java.text.MessageFormat.makeFormat(MessageFormat.java:1420)
at java.text.MessageFormat.applyPattern(MessageFormat.java:479)
at java.text.MessageFormat.<init>(MessageFormat.java:363)
at java.text.MessageFormat.format(MessageFormat.java:835)
at com.sun.faces.util.MessageUtils.getExceptionMessageString(MessageUtils.java:396)
at com.sun.faces.mgbean.BeanBuilder$Expression.validateLifespan(BeanBuilder.java:604)
at com.sun.faces.mgbean.BeanBuilder$Expression.<init>(BeanBuilder.java:553)
at com.sun.faces.mgbean.ManagedBeanBuilder.bakeBeanProperty(ManagedBeanBuilder.java:363)
at com.sun.faces.mgbean.ManagedBeanBuilder.bake(ManagedBeanBuilder.java:107)
... 49 more
Caused by: java.lang.NumberFormatException: For input string: "param.nodeId"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at java.text.MessageFormat.makeFormat(MessageFormat.java:1418)
... 57 more
any help ??
You are setting a value of an Integer to a String variable as the exception says
java.lang.NumberFormatException: For input string: "param.nodeId"
The nodeId variable should be an Integer variable .
OR
You can parse the Integer value using toString() method
Instead of #ManagedProperty ("# {param.nodeId}"), I made #ManagedProperty ("# {nodeId}") and it works:
#ManagedProperty("#{nodeId}")
private String nodeId;
#ManagedProperty("#{paramId}")
private String paramId;
#ManagedProperty("#{row}")
private int row;
#ManagedProperty("#{cel}")
private int cel;
#ManagedProperty("#{value}")
private String value;
Good morning, I have a problem with returning my database information (generated using the EF 6 code-first method) for my View Razor. The issue is that I'm wanting to return the information from inherited classes in the View, but they are not available, only the properties of the base class are presented, not those of the dependent classes.
The following are the Model, Controller, and View classes used:
Class ClientModel
public class Client
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClientId { get; set; }
[DataType(DataType.Date)]
public DateTime Birth { get; set; }
[Display(Name = "Telefone principal")]
public string Phone1 { get; set; }
[Display(Name = "Telefone Alternativo")]
public string Phone2 { get; set; }
public ICollection<OrcamentoContato> Contacts { get; set; }
public ICollection<Contrato> Contracts { get; set; }
}
Class FisicModel
public class PessoaFisica : Client
{
public TipoPessoa PersonType { get; set; }
[Required]
[Display(Name = "Nome completo*")]
[StringLength(250, ErrorMessage = "O campo é obrigatório.")]
public string Name { get; set; }
public string RG { get; set; }
[Required(ErrorMessage = "O campo CPF é obrigatório.")]
[StringLength(14)]
public string CPF { get; set; }
[Display(Name = "Filiação")]
public string Filiacao { get; set; }
[Display(Name = "Endereço")]
public string Address { get; set; }
}
Class JuridicModel
public class PessoaJuridica : Client
{
public TipoPessoa PersonType { get; set; }
[Required]
[Display(Name = "Razão Social*")]
[StringLength(200, ErrorMessage = "O campo é obrigatório.")]
public string SocialName { get; set; }
[Required]
[Display(Name = "CNPJ*")]
[StringLength(200, ErrorMessage = "O campo é obrigatório.")]
public string CNPJ { get; set; }
[Display(Name = "Inscrição Estadual")]
public string InscricaoEstadual { get; set; }
[Display(Name = "Inscrição Municipal")]
public string InscricaoMunicipal { get; set; }
[Display(Name = "Endereço")]
public string Address { get; set; }
public string ContactWith { get; set; }
}
Controller
public ActionResult Index()
{
var clients = db.Clients.ToList();
return View(clients);
}
Index View
#model IEnumerable<CabinePhoto.Models.Entidades.Client>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Birth)
</th>
<th>
#Html.DisplayNameFor(model => model.Phone1)
</th>
<th>
#Html.DisplayNameFor(model => model.Phone2)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Birth)
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone1)
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone2)
</td>
</tr>
}
IdentityModel
public DbSet<Client> Clients { get; set; }
public DbSet<PessoaFisica> PessoaFisica { get; set; }
public DbSet<PessoaJuridica> PessoaJuridica { get; set; }
All the information is stored in the same client table, since I'm using the form of inheritance by hierarchy, but in the view only the client model information is returned
I've been able to solve the problem. I'll leave here recorded what I did to solve the problem in respect to inheritance.
First, I created a ViewModel and put two ICollection properties, I modified the controller by adding the queries referring to the client table, but specifically bringing the required types and finally, I passed the ViewModel to the Index.cshtml and I used two foreachs to retrieve the information from According to the type specified, shown below:
ClientesiewModel.cs
public class ClientesViewModel
{
public IEnumerable<PessoaFisica> Fisica { get; set; }
public IEnumerable<PessoaJuridica> Juridica { get; set; }
}
controlle.cs
public ActionResult Index()
{
var cliente_fisico = db.Clientes.OfType<PessoaFisica>().ToList();
var cliente_juridico = db.Clientes.OfType<PessoaJuridica>().ToList();
var cliente = db.Clientes.ToList();
ClientesViewModel clientes = new ClientesViewModel()
{
Fisica = cliente_fisico,
Juridica = cliente_juridico
};
return View(clientes);
}
View Index.cshtml
#model CabinePhoto.ViewModels.ClientesViewModel
<table class="table">
<tr>
<th>
#Html.DisplayName("Nome")
</th>
<th>
#Html.DisplayName("Telefone")
</th>
<th>
#Html.DisplayName("Telefone 2")
</th>
<th></th>
</tr>
#if (Model.Fisica != null || Model.Juridica != null)
{
foreach (var fisica in Model.Fisica)
{
<tr>
<td>
#Html.DisplayFor(modelItem => fisica.NomeCompleto)
</td>
<td>
#Html.DisplayFor(modelItem => fisica.TelefonePrincipal)
</td>
<td>
#Html.DisplayFor(modelItem => fisica.TelefoneAlternativo)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = fisica.ClienteId }) |
#Html.ActionLink("Details", "Details", new { id = fisica.ClienteId }) |
#Html.ActionLink("Delete", "Delete", new { id = fisica.ClienteId })
</td>
</tr>
}
foreach (var juridica in Model.Juridica)
{
<tr>
<td>
#Html.DisplayFor(modelItem => juridica.PessoaContato)
</td>
<td>
#Html.DisplayFor(modelItem => juridica.CNPJ)
</td>
<td>
#Html.DisplayFor(modelItem => juridica.TelefonePrincipal)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = juridica.ClienteId }) |
#Html.ActionLink("Details", "Details", new { id = juridica.ClienteId }) |
#Html.ActionLink("Delete", "Delete", new { id = juridica.ClienteId })
</td>
</tr>
}
}
</table>
Thanks for the help previously assigned
Suppose you have a variable like this in your controller.
Client c = new Client();
If you later wrote
c.ClientId = 1;
it would work perfectly.
Similarly, if you wrote
PessoaFisica p = new PessoaFisica ();
and later
p.Name = "abc";
it would also work.
However, if you wrote
Client c = new PessoaFisica();
c.Name = "abc";
It will fail to compile.
Along the same lines
#model IEnumerable <CabinePhoto.Models.Entidades.Client>
means static type of your Model is a collection of Client objects, it will only allow you to bind to properties defined in Client class.
Entity Framework actually returns the correct types, but you're effectively upcasting everything to Client by the variable type you're storing into and the model definition of the view. Essentially, you just need to cast to the right type. Unfortunately, there's no way to just know what type it should be after it's been upcasted. You'll have to conditionally check:
if (item is PessoaFisica)
{
var pessoaFiscica = (PessoaFisica)item;
// now you can access those derived typed properties off of `pessoaFiscica`
}
You can also use as and rely on the fact that it returns null when something can't be casted:
var pessoaFiscica = item as PessoaFisica;
if (pessoaFiscica != null)
{
// access PessoaFiscica properties
}
With C# 7.0, you can use the pattern matching syntax to streamline it a little:
if (item is PessoaFiscica pessoaFiscica)
{
// use `pessoaFiscica`
}
The pattern matching syntax also allows you use switch blocks, which may make things much easier on you:
switch (item)
{
case PessoaFisica pessoaFisica:
// do something with `PessoaFisica` instance
break;
case PessoaJuridica pessoaJuridica:
// do something with `PessoaJuridica` instance
break;
default:
// do something with generic `Client` instance
break;
}
I am calling partial view controller through J_Query, controller action(ListInventoryProduct) is called and execute without error( the list is populated). But the partial view is not displayed.
In browser Developer tool says it is internal server error.
I can't figure out what is the problem.
The following is my code.
Model:
public class InventoryProductsViewModel
{
public long Id { get; set; }
[Display(Name = "Product Name")]
public string Title { get; set; }
[Display(Name = "SubCategory Name")]
public string SubCategory { get; set; }
[Display(Name = "Balance")]
public int Balance { get; set; }
[Display(Name = "Count")]
public int InventoryCount { get; set; }
[Display(Name = "Difference")]
public string Difference { get; set; }
[Display(Name = "IMEINumber")]
public string IMEINumber { get; set; }
[Display(Name = "BarrcodesString")]
public string BarrcodesString { get; set; }
public long subId { get; set; }
// public List<Category> lstCategory { get; set; }
}
Controller Action
public ActionResult LoadInventoryProducts(long categoryId)
{
Session["Products"] = null;
Session["InventoryMissing"] = null;
var userSession = Session.GetSessionUserInfo();
if (userSession != null)
{
List<InventoryProductsViewModel> products = db.Products.Where(p => !p.IsDeleted && p.CompanyId == userSession.CompanyId && (categoryId == 0 || p.SubCategory.CategoryId == categoryId)).Select(p => new InventoryProductsViewModel { Id = p.Id, Title = p.Title, SubCategory = p.SubCategory.Title, IMEINumber = p.IMEINumber, Balance = (p.PurchasedQuantity - p.SoldQuantity) }).ToList(); //&& (subCategoryId == 0 || p.SubCategoryId == subCategoryId)
Session["Products"] = products;
if (Session["InventoryMissing"] == null)
{
Session["InventoryMissing"] = new List<InventoryMissing>();
return PartialView("ProductsPartialView", products);
}
else
{
return Redirect("~/Error/Error");
}
}
}
PartialView
#model List<ViewModel.InventoryProductsViewModel>
<table >
<tr>
<th>#Html.DisplayNameFor(Model[0].Title)</th>
<th>#Html.DisplayNameFor(Model[0].SubCategory)</th>
<th>#Html.Label("Balance")</th>
<th>#Html.Label("Count")</th>
<th>#Html.Label("Difference")</th>
<th>#Html.Label("IMEI Number")</th>
</tr>
#for (int i = 0; i < Model.Count(); i++ )
{
<tr id="#Model[i].Id">
<td>
#Html.Hidden(Model[i].subId)
#Html.DisplayFor(Model[i].Title)
</td>
<td>#Html.DisplayFor(Model[i].SubCategory)</td>
<td class="balance">#Html.DisplayFor(Model[i].Balance)</td>
<td>#Html.EditorFor(Model[i].InventoryCount)</td>
<td class="difference">0</td>
<td>#Html.DisplayFor(modelItem =>Model[i].IMEINumber)</td>
</tr>
}
</table>
Html Helpers For Model were used which was creating problem.
Correct Helpers are as follow.
#model List<HiTechPOS.ViewModel.InventoryProductsViewModel>
<table class=" table table-striped table-advance table-hover">
<tr>
<th>
#Html.Label("Product Name")
</th>
<th>
#Html.Label("SubCategory Name")
</th>
<th>
#Html.Label("Balance")
</th>
<th>
#Html.Label("Count")
</th>
<th>
#Html.Label("Difference")
</th>
<th>
#Html.Label("IMEI Number")
</th>
</tr>
#for (int i = 0; i < Model.Count(); i++ )
{
<tr id="#Model[i].Id">
#*<td>
#Html.DisplayFor(modelItem => item.Id)
</td>*#
<td>
#Html.Hidden(Model[i].subId.ToString())
#Html.Label(Model[i].Title)
</td>
<td>
#Html.Label(Model[i].SubCategory)
</td>
<td class="balance">
#Html.Label(Model[i].Balance.ToString())
</td>
<td>
#Html.Editor(Model[i].InventoryCount.ToString())
</td>
<td class="difference">
#Html.Label(Model[i].Difference.ToString())
</td>
<td>
if(Model[i].IMEINumber == null)
{
#Html.Label("")
}
else
{
#Html.Label(Model[i].IMEINumber)
}
</td>
</tr>
}
I pass an instance of LoginViewModel to my view (Login)
When I click the submit button on the form another instance of LoginViewModel is created.
I can observe this because I put a breakpoint in the constructor.
Why does this happen and how can I fix it?
#using ViewModels
#model LoginViewModel
<form action="~/Home/VerifyLogin" method="post">
<table>
<tr>
<td>
User Name:
</td>
<td>
#Html.DropDownListFor(m => m.SelectedUserID, Model.UserList);
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
#Html.TextAreaFor(m => m.SelectedPassword);
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value ="Login" />
</td>
</tr>
</table>
</form>
Controller
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult RedirectToLogin()
{
return View("Login", new LoginViewModel());
}
[HttpPost]
public void VerifyLogin(LoginViewModel vm)
{
bool sucess = false;
// some logic
if(sucess)
RedirectToAction("ProjectList", "Project");
}
ViewModel
public class LoginViewModel :BaseViewModel
{
public IEnumerable<User> Users { get; private set; }
public IEnumerable<SelectListItem> UserList { get; private set; }
public int SelectedUserID { get; set; }
public string SelectedPassword { get; set; }
public LoginViewModel()
{
Users = DataService.GetUsers();
UserList = new SelectList(Users, "ID", "Name");
}
public bool Login(string userName, string password)
{
return true;
}
}
One is created here...
return View("Login", new LoginViewModel());
And one is created here
public void VerifyLogin(LoginViewModel vm)
The model binder creates objects and fills them with the parameters it receives from the request. This is normal operation.
To fix your problem, I would do this...
public ActionResult RedirectToLogin()
{
var vm = new LoginViewModel()
{
Users = DataService.GetUsers();
UserList = new SelectList(Users, "ID", "Name");
};
return View("Login", vm);
}
public LoginViewModel()
{
//Removed code
}
I have the following model in my MVC 4 Internet Application
public class EventModel
{
public int EventId { get; set;}
public string EventTitle { get; set;}
public string ImageUrl { get; set;}
public string VideoUrl { get;set}
}
Here's the Create.cshtml code for the Image and Video
#using(Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div>
#Html.LabelFor(model =>model.ImageUrl)
</div>
<div>
#Html.EditorFor(model =>model.ImageUrl)
#Html.ValidationMessageFor(model =>model.ImageUrl)
</div>
<div>
#Html.LabelFor(model =>model.VideoUrl)
</div>
<div>
#Html.EditorFor(model =>model.VideoUrl)
#Html.ValidationMessageFor(model =>Video.ImageUrl)
</div>
}
This is my controller code for the post method on create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EventModel eventmodel)
{
if (ModelState.IsValid)
{
_db.EventModels.Add(eventmodel);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(eventmodel);
}
How can I make the create page display buttons to upload image from the users computer. How do i modify my controller action to store the paths on the database and then how do I retrieve the image on the index.cshtml page.
For file uploading try this:
In controller:
[HttpPost]
public ActionResult Create(EventModel eventmodel, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
var filename = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
file.SaveAs(path);
tyre.Url = filename;
_db.EventModels.AddObject(eventmodel);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(eventmodel);
}
And View:
<div>
Image
<input type="file" name="file" id="file" />
#Html.HiddenFor( model => model.ImageUrl)
#Html.ValidationMessageFor( model => model.Url )
</div>