I am working on developing on a voting page mechanism. Here I will have the List of questions and against each question I have 3 options(I am using radio buttons). I have attached my View and Controller method. I am getting the value saved to DB correctly, but my problem is I am able to select multiple options where radio buttons are used. I want to make sure that, if one option is selected for a question the other options must be automatically deselected, which is not happening for me.
My View :
#using (Html.BeginForm())
{
<div>
#foreach (var a in ViewBag.Questions)
{
<h4>#a.Questions</h4>
<div>
#foreach (var b in Model)
{
if (b.QuestionsID == a.id)
{
#Html.RadioButton(b.AnswersOptions,
new {Answerid= b.id, Questionid=a.id })
#b.AnswersOptions
}
}
</div>
}
</div>
<br/>
<div >
<input type="submit" value="Vote Now!!"
onclick="return confirm('Are you sure you want to
submit your choices?');"/>
</div>
}
My Controller :
public ActionResult VotingResult_Post(FormCollection resultcollection)
{
int resultcollectionCount = resultcollection.Count;
if (resultcollectionCount == CountofQuestionsDisplayed)
{
for (int i = 0; i < resultcollectionCount; i++)
{
string SelectedIDArray = resultcollection[i];
string SelectedAnswerIDValue = GetValue("Answerid", SelectedIDArray);
string SelectedQuestionID = GetValue("Questionid", SelectedIDArray);
InsertUsersReponses(SelectedQuestionID, SelectedAnswerIDValue);
}
}
List<Voting_Questions> QuesList = PopulateQuestions();
ViewBag.Questions = QuesList;
List<Voting_Answers> Answers = aobj.Voting_Answers.ToList();
return View(Answers);
}
You need an HTML helper like the following
public static System.Web.Mvc.MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
string ForFormat = String.Empty;
if (listOfValues != null)
{
// Create a radio button for each item in the list
// need to create correct ID here
var baseID = metaData.PropertyName;
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", baseID, item.Value);
// Create and populate a radio button using the existing html helpers
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
// extracting the text for="##" from the label and using this for the control ID
// ASSUMES the format<label for="TestRadio_1">Line 1</label> and splitting on the quote means that the required value is in the second cell of the array
String[] temp = label.ToString().Split('"');
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = temp[1] }).ToHtmlString();
// Create the html string that will be returned to the client
// e.g. <input data-val="true" data-val-required="Option1" id="TestRadio_1" name="TestRadio" type="radio" value="1" /><label for="TestRadio_1">Line 1</label>
// e.g. <input data-val="true" data-val-required="Option2" id="TestRadio_2" name="TestRadio" type="radio" value="2" /><label for="TestRadio_2">Line 2</label>
sb.AppendFormat("<div class=\"RadioButtonList\">{0}{1}</div>", radio, label);
}
}
return MvcHtmlString.Create(sb.ToString());
which is called as follows:
#Html.ValidationMessageFor(m => m.myProperty)
#Html.LabelFor(m => m.myProperty, new { #class = "editor-label control-label" })
<div class="editor-field controls radio">
#Html.RadioButtonForSelectList(
m => m.myProperty,
ListOfOptionsForRadioButton
)
</div>
The markup is for Bootstrap.
Related
The answer I am sure is simple. I have a <select> with a list of values. For edit mode, I want the drop down to show the current value and have the selected when the view renders. And also when the form is submitted take a possible new selected value and pass it back to the controller. Any help would be greatly appreciated.
From the view:
<td style="padding:15px">
<label asp-for="OrganizationTypeId" class="form-control-label" style="font-weight:bold">Organization</label>
<select asp-for="OrganizationTypeId" class="form-control" style="width:450px" asp-items="#(new SelectList(Model.orgTypes, "Id", "OrganizationName"))">
<option value="" disabled hidden selected>Select Organization....</option>
</select>
</td>
Code in the controller:
dr = _electedOfficials.getDeputyReg(jurisdictionId, Id);
dr.orgTypes = _electedOfficials.GetOrganizationTypes(jurisdictionId);
return View(dr);
OrgTypes class
public int Id { get; set; }
public string OrganizationName { get; set; }
One of the solutions is preparing list of the SelectListItem and return the selected item Id to the controller:
public ActionResult Index()
{
// ...
dr.orgTypes = _electedOfficials.GetOrganizationTypes(jurisdictionId);
var model = dr.orgTypes.Select(d => new SelectListItem() { Selected = (d.Id == /* id of default selection*/), Text = d.OrganizationName, Value = d.Id.ToString() }).ToList();
return View(model);
}
[HttpPost]
public ActionResult Index(int? seletedId)
{
if (ModelState.IsValid && seletedId.HasValue)
{
// Processing the selected value...
}
return RedirectToAction("Index");
}
In the view:
#model IEnumerable<SelectListItem>
<script type="text/javascript">
$(document).ready(function () {
var e = document.getElementById("OrgTypesList");
$("#SeletedId").val(e.options[e.selectedIndex].value);
});
function changefunc(val) {
$("#SeletedId").val($("#OrgTypesList").val());
}
</script>
#using (Html.BeginForm("Index", "Home"))
{
#* To pass `SeletedId` to controller *#
<input id="SeletedId" name="SeletedId" type="hidden" />
<label asp-for="OrganizationTypeId" class="form-control-label" style="font-weight:bold">Organization</label>
#Html.DropDownList("OrgTypesList", Model, "Select Organization...", new { #class = "form-control", #onchange = "changefunc(this.value)" })
<button type="submit" class="btn btn-primary">Save</button>
}
I have a requirement to have different forms for different clients which can all be configured in the background (in the end in a database)
My initial idea is to create an object for "Form" which has a "Dictionary of FormItem" to describe the form fields.
I can then new up a dynamic form by doing the following (this would come from the database / service):
private Form GetFormData()
{
var dict = new Dictionary<string, FormItem>();
dict.Add("FirstName", new FormItem()
{
FieldType = Core.Web.FieldType.TextBox,
FieldName = "FirstName",
Label = "FieldFirstNameLabel",
Value = "FName"
});
dict.Add("LastName", new FormItem()
{
FieldType = Core.Web.FieldType.TextBox,
FieldName = "LastName",
Label = "FieldLastNameLabel",
Value = "LName"
});
dict.Add("Submit", new FormItem()
{
FieldType = Core.Web.FieldType.Submit,
FieldName = "Submit",
Label = null,
Value = "Submit"
});
var form = new Form()
{
Method = "Post",
Action = "Index",
FormItems = dict
};
return form;
}
Inside my Controller I can get the form data and pass that into the view
public IActionResult Index()
{
var formSetup = GetFormData(); // This will call into the service and get the form and the values
return View(formSetup);
}
Inside the view I call out to a HtmlHelper for each of the FormItems
#model Form
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#using FormsSpike.Core.Web
#{
ViewData["Title"] = "Home Page";
}
#using (Html.BeginForm(Model.Action, "Home", FormMethod.Post))
{
foreach (var item in Model.FormItems)
{
#Html.FieldFor(item);
}
}
Then when posting back I have to loop through the form variables and match them up again. This feels very old school I would expect would be done in a model binder of some sort.
[HttpPost]
public IActionResult Index(IFormCollection form)
{
var formSetup = GetFormData();
foreach (var formitem in form)
{
var submittedformItem = formitem;
if (formSetup.FormItems.Any(w => w.Key == submittedformItem.Key))
{
FormItem formItemTemp = formSetup.FormItems.Single(w => w.Key == submittedformItem.Key).Value;
formItemTemp.Value = submittedformItem.Value;
}
}
return View("Index", formSetup);
}
This I can then run through some mapping which would update the database in the background.
My problem is that this just feels wrong :o{
Also I have used a very simple HtmlHelper but I can't really use the standard htmlHelpers (such as LabelFor) to create the forms as there is no model to bind to..
public static HtmlString FieldFor(this IHtmlHelper html, KeyValuePair<string, FormItem> item)
{
string stringformat = "";
switch (item.Value.FieldType)
{
case FieldType.TextBox:
stringformat = $"<div class='formItem'><label for='item.Key'>{item.Value.Label}</label><input type='text' id='{item.Key}' name='{item.Key}' value='{item.Value.Value}' /></ div >";
break;
case FieldType.Number:
stringformat = $"<div class='formItem'><label for='item.Key'>{item.Value.Label}</label><input type='number' id='{item.Key}' name='{item.Key}' value='{item.Value.Value}' /></ div >";
break;
case FieldType.Submit:
stringformat = $"<input type='submit' name='{item.Key}' value='{item.Value.Value}'>";
break;
default:
break;
}
return new HtmlString(stringformat);
}
Also the validation will not work as the attributes (for example RequiredAttribute for RegExAttribute) are not there.
Am I having the wrong approach to this or is there a more defined way to complete forms like this?
Is there a way to create a dynamic ViewModel which could be created from the origional setup and still keep all the MVC richness?
You can do this using my FormFactory library.
By default it reflects against a view model to produce a PropertyVm[] array:
```
var vm = new MyFormViewModel
{
OperatingSystem = "IOS",
OperatingSystem_choices = new[]{"IOS", "Android",};
};
Html.PropertiesFor(vm).Render(Html);
```
but you can also create the properties programatically, so you could load settings from a database then create PropertyVm.
This is a snippet from a Linqpad script.
```
//import-package FormFactory
//import-package FormFactory.RazorGenerator
void Main()
{
var properties = new[]{
new PropertyVm(typeof(string), "username"){
DisplayName = "Username",
NotOptional = true,
},
new PropertyVm(typeof(string), "password"){
DisplayName = "Password",
NotOptional = true,
GetCustomAttributes = () => new object[]{ new DataTypeAttribute(DataType.Password) }
}
};
var html = FormFactory.RazorEngine.PropertyRenderExtension.Render(properties, new FormFactory.RazorEngine.RazorTemplateHtmlHelper());
Util.RawHtml(html.ToEncodedString()).Dump(); //Renders html for a username and password field.
}
```
Theres a demo site with examples of the various features you can set up (e.g. nested collections, autocomplete, datepickers etc.)
I'm going to put my solution here since I found this searching 'how to create a dynamic form in mvc core.' I did not want to use a 3rd party library.
Model:
public class IndexViewModel
{
public Dictionary<int, DetailTemplateItem> FormBody { get; set; }
public string EmailAddress { get; set; }
public string templateName { get; set; }
}
cshtml
<form asp-action="ProcessResultsDetails" asp-controller="home" method="post">
<div class="form-group">
<label asp-for=#Model.EmailAddress class="control-label"></label>
<input asp-for=#Model.EmailAddress class="form-control" />
</div>
#foreach (var key in Model.FormBody.Keys)
{
<div class="form-group">
<label asp-for="#Model.FormBody[key].Name" class="control-label">#Model.FormBody[key].Name</label>
<input asp-for="#Model.FormBody[key].Value" class="form-control" value="#Model.FormBody[key].Value"/>
<input type="hidden" asp-for="#Model.FormBody[key].Name"/>
</div>
}
<input type="hidden" asp-for="templateName" />
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
You can use JJMasterData, it can create dynamic forms from your tables at runtime or compile time. Supports both .NET 6 and .NET Framework 4.8.
After setting up the package, access /en-us/DataDictionary in your browser
Create a Data Dictionary adding your table name
Click on More, Get Scripts, Execute Stored Procedures and then click on Preview and check it out
To use your CRUD at runtime, go to en-us/MasterData/Form/Render/{YOUR_DICTIONARY}
To use your CRUD at a specific page or customize at compile time, follow the example below:
At your Controller:
public IActionResult Index(string dictionaryName)
{
var form = new JJFormView("YourDataDictionary");
form.FormElement.Title = "Example of compile time customization"
var runtimeField = new FormElementField();
runtimeField.Label = "Field Label";
runtimeField.Name = "FieldName";
runtimeField.DataType = FieldType.Text;
runtimeField.VisibleExpression = "exp:{pagestate}='INSERT'";
runtimeField.Component = FormComponent.Text;
runtimeField.DataBehavior = FieldBehavior.Virtual; //Virtual means the field does not exist in the database.
runtimeField.CssClass = "col-sm-4";
form.FormElement.Fields.Add(runtimeField);
return View(form);
}
At your View:
#using JJMasterData.Web.Extensions
#model JJFormView
#using (Html.BeginForm())
{
#Model.GetHtmlString()
}
In certain cases I want to display SelectList object not using DropDownListFor helper. Instead, I want to create a helper that iterates over the SelectListItems, and draw something different.
I have created an EditorTemplate:
#model RadioButtonOptions
<div class=" switch-field noselect" style="padding-left: 0px;">
#foreach (SelectListItem op in Model.Values.Items)
{
var idLabelF = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "_" + op.Value;
var esChecked = "";
if (op.Selected)
{
esChecked = "checked";
}
<input type="radio" id="#idLabelF" name="#(ViewData.TemplateInfo.GetFullHtmlFieldName(""))" value="#op.Value" #esChecked />
<label for="#idLabelF" style="width: 100px;">#op.Text</label>
}
</div>
The RadioButtonOptions class is a ViewModel:
public class RadioButtonOptions
{
public SelectList Values { get; set; }
}
The final resul looks like this:
My ViewModel is like this (simplified):
public class MainVisitVM
{
public MainVisit Visit { get; set; }
public RadioButtonOptions VisitOptions { get; set; }
}
And I use it in Razor View as:
<div class="clearfix">
#Html.LabelFor(x=> x.Visit.Tipo)
<div class="input">
#Html.EditorFor(x=> x.VisitOptions ) //HERE
</div>
</div>
The problem I have is that I want this to work more like the DropDownListFor, so the lamda expresion I pass is the property holding the selected value, and then just pass the SelectList object (or a custom list).
<div class="clearfix">
#Html.LabelFor(x=> x.Visit.Tipo)
<div class="input">
#Html.CustomDropDownListFor(x=> x.Visit.Tipo, Model.VisitOptions ) //This would be ideal!!
</div>
</div>
So, I think doing this using EditorTemplates will not be possible.
Any idea in how to accomplish this?
Thanks to #StephenMuecke suggestion, I ended up with this HtmlHelper extension method:
public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
SelectList listOfValues)
{
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
if (listOfValues == null) return MvcHtmlString.Create(string.Empty);
var wrapperDiv = new TagBuilder("div");
wrapperDiv.AddCssClass("switch-field noselect");
wrapperDiv.Attributes.Add("style", "padding-left: 0px;");
var sb = new StringBuilder();
foreach (SelectListItem item in listOfValues)
{
var idLabelF = htmlFieldName.Replace(".","_") + "_" + item.Value;
var label = htmlHelper.Label(idLabelF, item.Text, new { style = "width: 100px;" }).ToHtmlString();
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = idLabelF }).ToHtmlString();
sb.AppendFormat("{0}{1}", radio, label);
}
wrapperDiv.InnerHtml = sb.ToString();
return MvcHtmlString.Create(wrapperDiv.ToString());
}
Not particulary proud of my htmlFieldName.Replace(".","_"), but works.
We are working on Kendo MVC UI, where we are sending the data from one view to another view, all the data(testbox, dropdown) are getting passed to the next view except the attachments(pdf,xlsx).
Below is the code which in the controller which we have written to capture from view and save the data and pass the same data to the another view and bind the data to the kendo controls(upload control also)
public ActionResult SaveData(System.Web.Mvc.FormCollection form, IEnumerable<HttpPostedFileBase> files) // insert operation
{
//*************************//
if (form != null)
{
string ddluserexceptioncategory = Convert.ToString(form["txtexceptioncategory"], CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(ddluserexceptioncategory))
{
ddluserexceptioncategory = ddluserexceptioncategory.Trim();
}
if (ddluserexceptioncategory == "User Management")
{
//Bind the data to the class object(_clsObj)
if (files != null)
{
TempData["FileName"] = files;
_clsObj.Files = files;
}
TempData["SecondViewData"] = _clsObj;
return RedirectToAction("ExceptionType", "Home", new { id = 0, regionId = _clsObj.RegionId, status1 = "New,In Progress", keyword1 = string.Empty });
}
}
string regions = "", statusValue = "";
if (form != null)
{
regions = form["hiddenregionselected"] + "";
statusValue = form["hiddenstatusselected"] + "";
}
return RedirectToAction("homepage", "Home", new { region = regions, status = statusValue });
}
Below is the code which we bind the request to the second
#if (TempData["FileName"] != null)
{
IEnumerable<HttpPostedFileBase> firstFile = (IEnumerable<HttpPostedFileBase>)TempData["FileName"];
<div class="k-dropzone">
<div class="k-button k-upload-button">
<input name="files" type="file" data-role="upload" multiple="multiple" autocomplete="off" tabindex="-1" class="valid" style="display: none;">
<input id="files" name="files" type="file" data-role="upload" multiple="multiple" autocomplete="off">
<ul id="files1" class="k-upload-files k-reset">
#foreach (var file in firstFile)
{
string filename= Path.GetFileName(file.FileName);
<li class="k-file" data-uid="7aa03676-4dac-468e-b34a-99ac44d23040">
<span class="k-icon k-success">uploaded</span>
<span class="k-filename" title="#filename">#filename</span>
<strong class="k-upload-status">
<span class="k-icon k-delete"></span>
</strong>
</li>
}
</ul>
</div>
</div>
<script>
jQuery(function()
{jQuery("#files").kendoUpload(
{"select":uploadselect,
"localization":{"select":"Browse file",
"headerStatusUploading":"uploading..",
"headerStatusUploaded":"uploded.."},
"async":{"saveUrl":"/Home/Save",
"autoUpload":false,"removeUrl":
"/Home/Remove"}});});
</script>
}
else
{
#(Html.Kendo().Upload().Name("files").Async(a => a.Save("Save", "Home").Remove("Remove", "Home").AutoUpload(false)).Multiple(true).Messages(m =>
{
m.Select("Browse file");
}).Events(events => events.Select("uploadselect")))
}
Any suggestions or help is much appreciated.
My guess is that the issue is coming from using TempData to get this data from your markup to your controller or vice versa.
As you are likely aware, anything you put into TempData is discarded after the next request completes (Using Tempdata in ASP.NET MVC - Best practice, http://www.codeproject.com/Articles/476967/What-is-ViewData-ViewBag-and-TempData-MVC-Option).
I would suggest to try using the ViewBag to prove this theory. If it proves out you might think about passing this data as part of a complex object instead of using MVC's data dictionaries.
hi I have MVC Razor application as e catalog and I used drop down-list to bind data from DB but the DDl bind the same value from DB as if I have three categories " x , Y , Z" the DDL returned similar values " Z ,Z , Z ".As it have the last value "y" . also I tried to insert the selected value "ID" to DB when user selected the item from DDL but I couldn't and it returned false selected value.
public class CategoryController : Controller
{
private AndriodContext db = new AndriodContext();
List<SelectListItem> items = new List<SelectListItem>();
List<string> category = new List<string>();
SelectListItem s = new SelectListItem();
//
// GET: /Category/
public ActionResult Index()
{
var x = db.Categories.Where(y => y.Active == true).ToList();
return View(x);
}
public ActionResult Create()
{
var data = db.Categories.ToList().Distinct();
List<string> x = new List<string>();
foreach (var t in data)
{
s.Text = t.Name;
s.Value = t.Cat_ID.ToString();
items.Add(s);
}
ViewBag.Parent = items;
return View();
}
//
// POST: /Category/Create
[HttpPost]
public ActionResult Create(Category category, IEnumerable<HttpPostedFileBase> files)
{
var data = db.Categories.ToList().Distinct();
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in data)
{
SelectListItem s = new SelectListItem();
s.Text = t.Name;
s.Value = t.Cat_ID.ToString();
items.Add(s);
if (s.Selected)
{ category.Parent_ID = int.Parse(s.Value); }
}
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
}
#using (Html.BeginForm("Create", "Category", FormMethod.Post, new { enctype = "multipart/form-data", #data_ajax = "false" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend></legend>
<div class="editor-field create-Bt3">
#Html.DropDownList("Parent", new SelectList(ViewBag.Parent, "Value", "Text"), "- Select Parent -")
</div>
<div>
<p class="create-Bt ">
<input type="submit" value="Create" />
</p>
</div>
<br />
<br />
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</fieldset>
}
you need to import jquery 1.7.1.min.js(DOM) in viewpage :
get the jquery DOM from jquery website(http://blog.jquery.com/2011/11/21/jquery-1-7-1-released/).
then in button click (<input type="submit" value="Create" onclick="GetDropDownValue();"/>) :
wrote a javascript function :
<script type="text/javascript" language="javascript">
function GetDropDownValue()
{
$("#hdnParentId").val($("#Parent").val());
}
</script>
The best practice to use a model to bind the dropdownlist instead of ViewBag.
If you don't want to use model the you can do one trick.
you put a hidden field(<input type="hidden" name="hdnParent" id="hdnParentId" />) in view page and calculate selected value of dropdownlis by simple jquery using :
$("#Parent").val();.
make the dropdownlist :
#Html.DropDownList("Parent", new SelectList(ViewBag.Parent, "Value", "Text"), "- Select Parent -",new{ id="Parent" });
After that you get a string parameter in HTTPPOST in controller :
[HttpPost]
public ActionResult Create(string hdnParent) //hdnParent is the name of dropdownlist
{
//now you can get the seleced value from "hdnParent".
//do the stuffs
return View();
}