Coder Social home page Coder Social logo

mcintyre321 / formfactory Goto Github PK

View Code? Open in Web Editor NEW
304.0 42.0 102.0 8.44 MB

MVC5, Core or standalone - Generate rich HTML5 forms from your ViewModels, or build them programatically

Home Page: http://formfactoryaspmvc.azurewebsites.net/

License: MIT License

C# 53.33% CSS 4.45% JavaScript 24.44% HTML 17.76% ASP.NET 0.03%
asp-mvc asp-net-core form-builder component-driven

formfactory's Introduction

FormFactory - dynamic HTML form engine

Visit http://formfactoryaspmvc.azurewebsites.net/ for live documentation and to see what FormFactory can do!

Installation

For ASP.NET MVC 5

install-package FormFactory install-package FormFactory.AspMvc install-package EmbeddedResourceVirtualPathProvider * (or you can install FormFactory.Templates if you don't want to use the EmbeddedResourceVirtualPathProvider)

For ASP.NET MVC Core

install-package FormFactory install-package FormFactory.AspNetCore configure core to serve embedded files - see startup.cs lines 36 and 60

For both

Add the assets to your page <link href="/Content/FormFactory/FormFactory.css" rel="stylesheet" type="text/css"/> <script src="/Scripts/FormFactory/FormFactory.js" type="text/javascript"></script>

How to use it

Inside an cshtml file: @FF.PropertiesFor(someObject).Render(Html);

.PropertiesFor(someObject) will reflect over the someObject and create an enumerable of PropertyVm objects, and .Render(Html) will render each object out the page

See the documentation site for how to mark up your viewmodel

formfactory's People

Contributors

bitdeli-chef avatar bmaster001 avatar budsy avatar gingters avatar gitter-badger avatar jensj avatar mcintyre321 avatar morten-hogseth avatar nickcoad avatar reiphil avatar simonjduff avatar tanis2000 avatar timiles avatar vbocan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

formfactory's Issues

Handle sortable in nested collections recipe

Hi, I am using your forms for nested collections πŸ‘ . Can you add please/handle sortable and drag drop in nested collections, if you want I can post a couple of samples.

thanks

FormFactory.Templates has wrong build action for content files

I created an empty ASP.NET MVC project and added the following NuGet packages:

  • FormFactory
  • FormFactory.AspMvc
  • FormFactory.Templates

In one of the .cshtml files I added the following:

@{ 
    var model = new AutoCompleteExample();
}
@(FF.PropertiesFor(model).Render(Html))

At runtime, I get a System.InvalidOperationException with this text:

The partial view 'FormFactory/Form.Property' was not found or no view engine supports the searched locations.

Indeed, the ~/Views/Shared/FormFactory is empty but I understand that the folder can be safely deleted if I don't plan to customize the views.

Any help appreciated.

Caching generated views

Hi!

I was reading FF code yesterday and a doubt appeared: Does FF generate views everytime it receives a request? Does it have a way of caching/storing generated views somewhere else (ie: Database or file)?

I have a lot of register/fields metadata stored in a database, and I'll use IL Generation for the classes with all data annotations, restrictions and validations. I'll hash these classes so, with every created field, there will be a new version of the same class, stored inside database.

Thank you for all effort put in this project.

How to handle form submit + put values into a view model

Hello,
FF works great when creating a form programatically (fields are displaying well).
But when I submit the form, I'd like to find a efficient way to bind to the model. Do you have an example about this? Or any suggestion?
Thanks

FormFactory with table/grid row & target CRUD actions

Hi Harry, can you please add some help on handling a table/grid i.e row based view, inside a form with data collections.

Also, the CRUD options with row updates. I see you have the datatables already in a sep lib, is that embedded with form factory.

lastly how does the virtual path provider help.

thanks

Update to 4.6.1

Hi, can you please update to current 4.6.1 should be straight forward.
thanks

Unable to move items up in sortable list

    //ICollections get rendered as re-orderable lists
    public ICollection<Movie> TopMovies { get; set; }

Love it!!

  1. The corresponding code does not sort up, i.e. try to move a list item up, it does not move up. How does the list know to sort, in the code, I see no configuration.
    
  2. How is security handled, is just standard role checking at the class level, I ask because it would be nice to have a way to map roles to forms and models. (I'll add it o the feature request :)
    

Usage question

From StackOverflow

Hi,

  1. in this snippet using (var form = Html.FormForAction((HomeController c, string p0, string p1, bool > p2, string p3) => c.SignIn(p0, p1, p2, p3))) there are 4 vairables, but the action takes 3 variables,
    2)How is the submit being performed in the second form, can you expand the documentation a little please
  2. how can I do Lat Long, Fa-Icons? – aggie yesterday

Roadmap, suggestions

This has become so vital to my development, not sure why others are not using it.

  • Can we please get a small roadmap going, at least one or two features so people can contribute or influence it. I want to hear more on where this is going.
  • For other devs - It takes some time to get fluent in getting used to FormFactory, but after then its worth the investment.

Its like Zencoding for C#, it gives you the same boost!

Dependencies of default FormFactory templates

I am getting a bit lost with the dependencies for the default templates with FormFactory. I see that I can modify these templates in order to implement the behavior and styles I want, but it does not seem to work out of the box.

Is there a list of javascript libraries the FormFactory templates depend on?

Localization

Is there a possibility to translate/localize the validation messages (e.g. RequiredAttribute)?

Need help with usage

Hi,
i'm trying to use FormFactory in one of my open source projects.
I like it how it generates my first form, but I'm a bit lost in how to use the features.
I am using ASP.NET Core 2 Razor Pages.

So my main two questions are:
How can I enable validation? My required fields i.e. aren't validated and I can post the form without needing to fill in required fields.

When the form gets posted, what do I need to do to get the entered & posted data into my model to further process it?

Thanks in advance

LabelOnRightAttribute usage

I tried adding new FormFactory.Attributes.LabelOnRightAttribute() to the GetCustomAttributes field list (in declarative programmable model example) for a checkbox. It rendered the following:

"if (Model.GetCustomAttributes().OfType ().Any()) { } else //if not required, then it is possible to post a false value, which means we need a hidden field as unchecked checkboxes aren't posted. sigh. { } Checkbox label here"

This wasn't quite what I expected. Is there a correct way to get the label for a checkbox to render to the right of the box? A checkbox works great with the default label on the left.

Bootstrap version

Once again another great genius component!

This is more a request and not a bug, would be great if we could configure the form helper to also pick up a version of bootstrap BS 3.3 or BS 4.x during its form building process.

NullReferenceException while returning invalid vievmodel

When viewmodel is passed again to form as invalid (ModelState.IsValid == false), form in my Razor view throws System.NullReferenceException.

My viewmodel

public class CategoryViewModel
    {
        public CategoryViewModel()
        {
            CategoryProperties = new List<CategoryPropertyViewModel>();
        }

        [Hidden]
        public int Id { get; set; }

        [Required]
        [MaxLength(100)]
        [DisplayName("Category name")]
        public string Name { get; set; }
        
        [DisplayName("Base category")]
        public int BaseCategoryId { get; set; }

        public IEnumerable<int> BaseCategoryId_choices()
        {
            var categoryService = CategoryService.GetService();
            var data = categoryService.GetCategories();

            return data.Select(x => x.Id.DisplayName(x.Name));
        }

        public ICollection<CategoryPropertyViewModel> CategoryProperties { get; set; } 
    }

public class CategoryPropertyViewModel
    {
        [Hidden]
        public int Id { get; set; }

        [Required]
        [MaxLength(100)]
        [DisplayName("Property name")]
        public string Name { get; set; }

        [Required]
        [DisplayName("Property type")]
        public PropertyType PropertyType { get; set; }

        [Hidden]
        public int CategoryId { get; set; }
    }

My Razor view:

@using FormFactory
@using FormFactory.AspMvc
@model Reservations.DataUI.Models.CategoryViewModel

<h2>@ViewData["Title"]</h2>

@using(Html.BeginForm(ViewData["Action"].ToString(), "Categories", FormMethod.Post, new {@class = "form-horizontal", role = "form"}))
{
    @FF.PropertiesFor(Model).Render(Html)

    <button type="submit" class="btn btn-info">Save</button>
}

My POST controller method:

[HttpPost]
public ActionResult Add(CategoryViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View("Update", model);
    }
    return RedirectToAction("Index");
}

My GET controller method:

public ActionResult Add()
{
    ViewData["Title"] = "Add category";
    ViewData["Action"] = "Add";
    var model = new CategoryViewModel();
    return View("Update", model);
}

Stack trace:

ASP._Page_Views_Categories_Update_cshtml.Execute() in C:\Users\trawinski\Documents\reservations_clean\Reservations.DataUI\Views\Categories\Update.cshtml:7
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +270
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +122
   System.Web.WebPages.StartPage.RunPage() +63
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +100
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +131
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9765121
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Choices rendering incorrectly

When there are a set of choices defined on the ViewModel, the selectlist correctly displayed, but the options are also rendered as a bullet list.
It looks like the properties are not being selected to exclude _choices properties correctly.

Document DB - where column sizes are inconsistent

When the collections have inconsistent column sizes like MongoDB or something else, depending on the query the collection structure could be different/dynamic - is there a way to still have the form constructed from that returned collection.

Programatic Buttons

I'm trying to figure how to build a form programatically (with success), but I have no success trying to make appear the Summit button and trying to get the form values to the FormVm dynamic object that I create to build the form.

I would appreciate some tips on this.

Required attribute

Hello,
Form the beginning, here's part of my viewmodel, two sample properties:
[Required]
public string CompanyName { get; set; }

[Required]
[Radio]
public ContractType ContractType { get; set; }

Here's how I build form:

@{ var props = FF.PropertiesFor(Model); @props.Render(Html); }

When I post form and CompanyName is empty/null I don't get validation message that says CompanyName is required.
On the other hand when ContractType enum value is not set I get message that says ContractType is required.
It seems that Required on string properties does not work or I'm missusing it.
Could you clarify how to use that attribute?

Trying to get started with FormFactory.AspMvc

Sorry to ask such a naΓ―ve question, but I am just starting with FormFactory.AspMvc and haven't been able to get off ground. Downloaded Nuget packages (including AspMvc and Templates). Placed the following in one of my edit forms (cshtml): @Html.PropertiesFor(Model).Render(Html)

PropertiesFor is not recognized. No doubt doing something stupid. Thanks,
Craig

dropdown with preselect

I'm playing around with FormFactory to build programatically created forms. I noticed that setting the preselect value for a dropdown box, doesn't work - the "selected" attribute somehow doesn't make it to the generated html output. It's easy to reproduce: on the examples, remove the radioattribute from the Operating System optionlist... like this:

new PropertyVm(typeof(string), "os")
    {
        DisplayName = "Operating System",
        NotOptional = true,
        Choices = new List<>() {"OSX", "IOS", "Windows", "Android"},
        Value = "Windows" //Preselect windows
    }

You'll notice that the selected attribute for the Windows option isn't generated.

How to use this in WebForms?

Hello.
I wanna know if i can use this or something like this in WebForms, i need it very much, if you have idea or article or sample please give me.
Thank you

Posting PropertyVM to MVC controller

Hello,
All the example has it render propertyVM on MVC view, did some try to post the data from MVC to controller with the same PropertyVM object?

New Project - Enterprise Solution - Can forms be database driven?

Hi,

Note: this is a question, not an issue.

Is this Repo production ready, I have viewed the code and examples, and it looks very promising. One question i have is can the forms be generated at runtime driven from the data in a database?

As this is attribute driven, does that limit the forms to be bassed the attributes are assigned at design time?

Regards
John

PropertyVM ID's are not shown in the view, Change Date Format, Add Bootstrap classes

Hello mcintyre321!

I have an issue and two questions about PropertyVM:

The first problem that I have is: The Id's that I have assigned are not shown in the view.
The first question that I have is: How I can set a custom format in DateAttributes (PropertyVM with DateTime Format)?
The second question that I have is: How I can add Bootstrap classes to an PropertyVM?

Thanks a lot!

Cant open project in VS2013 or VS2015

Cant open project in VS2013 or VS2015

The formfactory XProj cant be loaded, FormFactory.AspnetCore cant be loaded and FormFactory.AspnetCore.Example wont load

What version of Visual Studio are you using?

Precompiler for speed

Is there a flag to pre-compile the forms for speed, it would also help to see what the formFactory is putting out to check during debug

πŸ‘

Disable edit for 1 or all property

Hi,
How can i disable edit for 1 or all property?
The goal is to let user see the property but not edit it , like for property in readonly .
Thank you

SelectListItem or similar to populate PropertyVM DropDown

Hello!

I'm using FormFactory in ASP .NET Core to create a form dynamically. I have to add a PropertyVM that will be a DropDown. In this DropDown I have to set the value of each option.

Before using FormFactory, I had all the options in an IList but when I add this IList in an PropertyVM then It cannot render the form.

**So there is a way to do the same that I was doing with SelectListItem in an PropertyVM?

Here you have the IList that I'm using (it's written in VB, but I think you will understand it easily):

Dim Sexo As IList(Of SelectListItem) =  New List(Of SelectListItem) From {
            New SelectListItem With {.Text = "Masculino",  .Value = "M"},
            New SelectListItem With {.Text = "Femenino",  .Value = "F"}
}

Thank You!

Embedded resource feature

This may just be an issue with my setup, but... when I got around to publishing my web project to a staging site, I discovered that the 'Embedded Resource' feature completely stopped working, unable to find the virtual paths for some reason. The dev version and the staging version of my app are as identical as I can make out, right down to asp.net version and server configuration parameters. I checked all the Dlls and files list, and everything seems to be there. I updated my nuget packages, checked my Mvc routing, checked versioning, etc. etc. Obviously some little detail is missing. Anyway, I worked around this issue by eliminating the Embedded resource files and references, then installed all the template files. This seems to work just fine now in terms of speed and whatnot, and I can tweak the templates more easily. I just wanted to share this experience.

Question: is there a way to hide a property at runtime?

I have a use case where I want to use the same form for both "add" and "update" operations using an EF model.

It works fine as long as I use the DataType attributes to set which properties to show, but what I would like to do is to set one of the property to be shown only in "add" mode and not on "update".

Is there any way to tell FormFactory that kind of information at runtime?

Thanks!

Validating a Form Post where All Properties are Added Programmatically

I'm attempting to implement the method below described on http://formfactoryaspmvc.azurewebsites.net/, but I can't figure out if the library already has the ability to perform server-side validation without a pre-built view model to map to on form post.

By default FF reflects against a view model to produce a PropertyVm[] array, but you can also create the properties programatically, e.g. you could load a form definition from a database

So I'm using my back-end code to build an array of PropertyVm objects, and then calling .Render() on that array to build out the form HTML. That part is working splendidly. However, when I hit the form submit button, I'm not sure how to identify the inputs and values and validate them against the same database-driven rules I used to generate the PropertyVm array I used initially.

Before I dive too deep into coding my own solution, I thought I'd ask if maybe there's something already pre-baked into FormFactory that I'm missing in the shuffle. Thank you!

Async methods support?

Hi, form factory supports only synchronous ActionResult type. Do you plan to add async Task<ActionResult>?

I mean Html.FormForAction

jQuery killed in Asp.Net Mvc

The EmbeddedResourceVirtualPathProvider kills my Mvc + Bootstrap app's jQuery is rendered nofunctional, as the jQuery object is no longer recognized. Is there an elegant way to fix this? I will figure it out eventually, but maybe someone has already encountered this issue?

Add Values to the choices

Normally when creating a form with user entry that uses select , radio buttons and other data entry elements like that, I prefer to have a different value from the displayed value, I was wondering if there is any way of doing that, while still Programmatically creating the form.
e.g

  new PropertyVm(typeof(string) , "number")
                    {
                        DisplayName = "Select a number",
                        NotOptional =false,
                        Choices = new List<string>(){"one","two","three"},
                        

                },

renders

<select name="number" class="form-control">
                <option value="one">one</option>
                <option value="two">two</option>
                <option value="three">three</option>
                <option value="four">four</option>
        </select>

but I want it render like

<select name="number" class="form-control">
                <option value="1">one</option>
                <option value="2">two</option>
                <option value="3">three</option>
                <option value="4">four</option>
        </select>

was wondering is there is any functionality that like?

Is it possible to have multi fields in the same row?

I have the form displaying and working well but from UI part, can some fields be configurable to display in the same row? I want to add col-* class but do not know how to inject. It's great if you could provide some guide. Thanks a lot !!

Unable to install package

Trying to run install-package FormFactory in Nuget, I get the following output:

Installing 'FormFactory 3.0.11'.
Successfully installed 'FormFactory 3.0.11'.
Adding 'FormFactory 3.0.11' to FormFactoryTestMvc.
Uninstalling 'FormFactory 3.0.11'.
Successfully uninstalled 'FormFactory 3.0.11'.
Install failed. Rolling back...
install-package : Could not install package 'FormFactory 3.0.11'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content 
files that are compatible with that framework. For more information, contact the package author.
At line:1 char:1
+ install-package FormFactory
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

Stack Overflow Exception

I'm having a hard time getting started with FormFactory. I've installed FormFactory and FormFactory.Templates via Nuget but keep getting a StackOverflowException with the following:

<form>
    @{
        var me = new Site { Name = "Hello World", Id = 55 };

        Html.PropertiesFor(me).Render();
    }
    <input type="submit" value="submit" />
</form>

I'm using MVC4.

How to render Nested ViewModels, collections

hi I saw the one sample on collections, fro ASP MVC 5

walking down the collection StudentWeekVM but I was not able to get it to work with 2 nesting levels - can you please show me how I would wire this up? and on submit does it submit the entire StudentWeekVM collection it contains

For ex. show the Student Week Schedule with student Hours,

  • showing days on top <monday, tuesday, >

  • and classes on the side like this image

       // the over all container/collection of `ClassTimeGroup`
      public class StudentWeekVM
      {
          public StudentWeekVM()
          {
              Records = new List<ClassTimeGroupVM>();
              Totals = new List<LabHoursEnteryVM>();
              for (int i = 0; i < 7; i++)
              {
                  Totals.Add(new LabHoursEnteryVM());
              }
          }
          [DisplayFormat(DataFormatString = "{0:dddd d MMMM yyyy}")]
          public DateTime WeekEnding { get; set; }
          public StudentVM Student { get; set; }
          public List<ClassTimeGroupVM> Records { get; set; }
          public List<LabHoursEnteryVM> Totals { get; set; }            
          public decimal GrandTotal { get; set; }
          public int SelectedProject { get; set; }
          public int SelectedClassDayOrNight { get; set; }
          public IEnumerable<SelectListItem> Projects { get; set; }
          public IEnumerable<SelectListItem> ClassDayOrNights { get; set; }
      }
    
    // a row of the class with the weekly hours <monday, tues etc>
      public class ClassTimeGroupVM
      {
          public ClassTimeGroupVM()
          {
              TimeRecords = new List<LabHoursEnteryVM>();
              Total = new LabHoursEnteryVM();
              for (int i = 0; i < 7; i++)
              {
                  TimeRecords.Add(new LabHoursEnteryVM());
              }
          }
          public ClassDayOrNightVM ClassDayOrNight { get; set; }
          public List<LabHoursEnteryVM> TimeRecords { get; set; }
          public LabHoursEnteryVM Total { get; set; }
      }
      public class ClassDayOrNightVM
      {
          public int ID { get; set; }
          public string Name { get; set; }
          public ClassesVM Project { get; set; }
      }
      public class LabHoursEnteryVM
      {
          public int? ID { get; set; }            
          public decimal Hours { get; set; }
      }
    

How to get the form values to the model?

If I have a model and I send this model to the View, Can I get the form values to the form automatically? or I should try JObject also the get the values one by one and update the model manually?

Can't get FormFactory.js to work

Hi,
I have created a new sample ASP.NET 4.7 Web Application project with MVC.
Installed packages FormFactory, FormFactory.AspMvc and EmbeddedResourceVirtualPathProvider.
Added the asset tags to the in .\Views\Shared\_Layout.cshtml

<link href="/Content/FormFactory/FormFactory.css" rel="stylesheet" type="text/css"/>
<script src="/Scripts/FormFactory/FormFactory.js" type="text/javascript"></script>

Then I have added a model class EditableCollectionsExample same as in your example.

using FormFactory.Attributes;
...
public class EditableCollectionsExample
{
        public EditableCollectionsExample()
        {
            TopMovies = new List<Movie>()
            {
                new Movie() {Title = "Fight Club"},
                new Movie() {Title = "The Silent Partner" },
                new Movie() {Title = "Bambi"},
            };
        }
        [Description("Writable ICollections get rendered as re-orderable lists")]
        public ICollection<Movie> TopMovies { get; set; }
}

public class Movie
{
        [Required]
        [StringLength(64, MinimumLength = 2)]
        public string Title { get; set; }
}

Added this to the Home\Index.cshtml view:

@using FormFactory
@using FormFactory.AspMvc;
...
<form>
  @{           
    var me = new EditableCollectionsExample();
    @(FF.PropertiesFor(me).Render(Html))
  }
  <input type="submit" value="submit" />
</form>

Then page renders the collection form as expected, however, none of the Add, Remove, MoveUp or MoveDown buttons hit their JavaScript actions.
In the console I see this error in FormFactory.js:
https://imgur.com/a/4AnMo
That's this line:

$(document).on("focus", ".ff-behaviour", function () {
    var behaviour = $(this).data("ff-behaviour");
    if (ff.behaviours[behaviour]) {
        ff.behaviours[behaviour](this);
    }
});

I have tried adding some of the other example model classes and none of their JavaScript actions worked.
Any idea what I could be doing wrong?

I admit I'm not a pro front-end developer, that's why I wanted to use your awesome framework... to avoid the hassle of writing all the client-side scripts just for the little more complex data-entry UI we are working on.

Thanks a lot,
Ondrej

Get Values from Dynamically Created PropertyVm[]

Posting to the action results in a null PropertyVM[]

I want to get the saved values from the server generated PropertyVM[].

I'm I missing something here?

public ActionResult Index()
       {
           var formModel = new[]
                   {
               new PropertyVm(typeof(string), "username")
               {
                   DisplayName = "Username",
                   NotOptional = true,
               },
               new PropertyVm(typeof(string), "password")
               {
                   DisplayName = "Password",
                   NotOptional = true,
                   GetCustomAttributes = () => new object[] {new PasswordAttribute()}
               },
               new PropertyVm(typeof(string), "os")
               {
                   DisplayName = "Operating System",
                   NotOptional = true,
                   Choices = new List<string>() {"OSX", "IOS", "Windows", "Android"},
                   Value = "Windows", //Preselect windows
                   GetCustomAttributes = () => new object[] {new RadioAttribute()},
               }
           };

           return View("Index", formModel);

       }

Index cshtml

<p>...will render this form:</p>
        @model PropertyVm[]
        @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
                @Model.Render(Html);

                <input type="submit" value="Submit" />
        }

Action result for post

        [HttpPost]
        public ActionResult Index(PropertyVm[] vm)
        {
            var results = vm; //this is always null
            return RedirectToAction("Index");
        }

How to dynamically disable an edit?

Hi,

I have a enum, and the user should select one of the entries in the enum with a radio box,
and a textbox which should only be enabled when a certain element in the dropdown is selected.

Example:

Please select an item:

  • FirstItem
  • SecondItem
  • ThirdItem
  • Other

If other, what other item did you select?: [Textbox] (should be editable only if Other is selected above.)

In short, I want to replicate the Fomerole Type from this reporting form but with a bit more validation logic: https://docs.google.com/forms/d/e/1FAIpQLSeYI4R29n-n6eMQTxoL_Nh5rF26NUGxQQqt5dOH7YCT2A1gzA/viewform

Besides that, I can't get it working.
I specified this:

[Display(Name = "Fumerole type")]
[Radio]
[Description("If your type isn't listed, please use the other.")]
public FumeroleType FumeroleType { get; set; }

With FumeroleType being my enum, but it renders as a dropdown and not as a radio button list.

Create button inside PropertyVM

Hello!

How I can do to create a button in an PropertyVM. I have tried the answer that Harry posted in this issue but I have no idea about how to create a button in XElement.

Please how I can make a button inside a PropertyVM, using XElement (or not using it if it's not done with XElement)?

Thanks a lot.

Localitzation and Validation Messages

Hello Harry!

I'm finishing my project with FormFactory and I'm trying to validate the data from my inputs. In ASP .NET Core you can set it like this:

public class SomeViewModel
{
   [Required(ErrorMessage = "Your elegant error message goes here")]
   public int ProductId { get; set; }
} 

But I haven't found any way to set it when I create my PropertyVms, so there is way to set my custom error message?

Another thing that I would like to change is the language that the NotOptional / Optional Label is shown. I would like to set it in Spanish.

Thank You!

Multiple options in a checkbox?

Just found this project. Looks quite interesting. I was wondering if it has a checkbox with which you can select multiple items (not the standard yes/no Boolean).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.