Dynamically add multiple fields to be validated using bootstrap validator - ruby-on-rails

I have gone through the example here. But it illustrates dynamic addition of a single input field. I have to add multiple dynamic input fields. How can I achieve it? Refer this example jsfiddle
I need to dynamically add all the three fields in the table row on clicking button through.

You can try somethings like this:
<form id="myForm" action="myAction">
<div class="row" id="line_1">
<div class="col-md-2 form-group">
<input type="text" class="form-control input-sm" id="idFirstField_1" name="firstField[]">
</div>
<div class="col-md-2 form-group">
<input type="text" class="form-control input-sm" id="idSecondField_1" name="secondField[]">
</div>
<div class="col-md-2 form-group">
<input type="text" class="form-control input-sm" id="idThirdField_1" name="thirdField[]">
</div>
</div>
<a id="cloneButton">add line</a>
</form>
In the JavaScript file you must to use the function clone() and to change the id of each input if you want:
$(document).ready(function () {
var count = 2;
$('#cloneButton').click(function () {
var klon = $('#line_1');
klon.clone().attr('id', 'line_' + (++count)).insertAfter($('#line_1'));
$('#line_' + count).children('div').children('input').each(function () {
$(this).val('');
var oldId = $(this).attr('id').split('_');
$(this).attr('id', oldId[0] + '_' + count);
});
});
//if you want to validate the fields, then you can use this code:
$('#myForm').bootstrapValidator({
fields: {
'firstField[]': {
validators: {
notEmpty: {
message: 'Enter a value'
}
}
},
'secondField[]': {
validators: {
notEmpty: {
message: 'Enter a value'
}
}
},
'thirdField[]': {
validators: {
notEmpty: {
message: 'Enter a value'
}
}
}
}
});
});
Now the bootstrap validation does not will work for cloned fields because you must to use in the JavaScript file somethings like this
$('#myForm').bootstrapValidator('addField', $option); //(from your link http://bootstrapvalidator.com/examples/adding-dynamic-field/ )
but who will contains all fields. I don't now how to do it.

Related

Loading partialView through ajax not working

i am trying to show order Summary through partial View and ajax.Request is going to server but my action method of Showsummary never hits. i want to summary of order through partial view.
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
var p = model.Packages.SelectMany(x => x.Packages).Select(y => new OrderPackagesViewModel()
{
PkgName = y.PkgName,
pkg_Id = y.id,
Ser_Id = y.Ser_Id,
Quantity = y.Quantity,
price = (y.TotalPrice - (y.DiscountPercent / 100 * y.TotalPrice)) * y.Quantity
}).ToList();
model.OrderPackages = p;
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
My Ajax
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
$.ajax({
type: "POST",
url: "/Order/Showsummary",
data: $("form.signup-form").serialize(),
success: function (data) {
console.log(data)
$('#page_2').hide();
$('#page_3').show();
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
})
//Html Code
<div id="page_1">
<input asp-for="cus_name" placeholder="First Name" >
<input asp-for="Email" placeholder="Email" >
<select asp-for="Country" class="ui search dropdown">
<option value="">Select Country</option>
<option value="AF">Afghanistan</option>
<option value="AX">Ă…land Islands</option>
</select>
<input asp-for="cus_phone" placeholder="Phone Number"/>
<select asp-for="FirstPreferences" class="custom-select mr-sm-2"
asp-items="#(newSelectList(Preferences))">
<option value="">Select</option>
</select>
<select asp-for="FirstPreferedTimeStart" class="menu">
<option value="">HH:MM</option>
<option value="00:00:00">00:00</option>
<option value="01:00:00">01:00</option>
</select>
<textarea asp-for="Message" class="form-control"> </textarea>
</div>
//Page2 details of packages available. It is list of GroupByServices which contain fields ser_id Ser_Name and List of ServicePackages.
<div id="page_2" style="display:none">
<div>
<h1 id="heading">Choose a Package!</h1>
</div>
<div class="buttons">
#foreach (var services in Model.Packages)
{
<a href="#service_#services.Ser_Id"><div class="logo-p">
<h2>#services.Ser_Name</h2></div></a>
}
</div>
<!-- packages -->
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="packages" id="service_#Model.Packages[i].Ser_Id">
<h1 id="custom-website-design">
#Model.Packages[i].Ser_Name
</h1>
<div class="packs-content">
#for (int j = 0; j < Model.Packages[i].Packages.Count(); j++)
{
<div class="pack1">
<div class="pack-price">
<div>
<input asp-for="#Model.Packages[i].Packages[j].id" hidden />
<input asp-for="#Model.Packages[i].Packages[j].PkgName" hidden />
<input asp-for="#Model.Packages[i].Packages[j].Ser_Id" hidden />
<input asp-for="#Model.Packages[i].Packages[j].Ser_Name" hidden />
<h1>#Model.Packages[i].Packages[j].PkgName</h1>
<p>#Model.Packages[i].Packages[j].Ser_Name PACKAGE</p>
</div>
<p>$#Model.Packages[i].Packages[j].TotalPrice</p>
<input asp-for="#Model.Packages[i].Packages[j].TotalPrice" hidden />
</div>
<div class="pack-features">
<div class=""></div>
#foreach (var features in Model.Packages[i].Packages[j].Description)
{
<h2>#features</h2>
}
</div>
<div class="pack-order">
<div class="row-1">
#{
double discount = (Model.Packages[i].Packages[j].DiscountPercent / 100 * Model.Packages[i].Packages[j].TotalPrice);
double PriceAfterDiscount = Model.Packages[i].Packages[j].TotalPrice - discount;
}
<p>SPECIAL DISCOUNT</p>
<P>-$#discount</P>
</div>
<div class="row-2">
<p>FINAL PRICE FOR LIMITED TIME</p>
</div>
<div class="row-3">
<a asp-controller="Packages" asp-action="Detail" asp-route-id="#Model.Packages[i].Packages[j].id" target="_blank">view details</a>
<h1>$#PriceAfterDiscount</h1>
<input asp-for="#Model.Packages[i].Packages[j].DiscountPercent" hidden />
</div>
<div class="row-4">
<h4>Add To Buying List</h4>
<div class="input-group mb-3 order-btn-pack">
<div class="input-group-prepend">
<div class="input-group-text">
<input asp-for="#Model.Packages[i].Packages[j].is_selected" aria-label="Checkbox for following text input">
</div>
</div>
<input asp-for="#Model.Packages[i].Packages[j].Quantity" value="1" min="1" required placeholder="Quantity" class="form-control" aria-label="Text input with checkbox">
</div>
</div>
<div class="row-5">
<p>Discuss this offer with expert</p>
<div class="discuss">
<p>12345467889</p>
<p id="chat-btn_10">Live Chat</p>
</div>
</div>
</div>
</div>
}
<input asp-for="HoldPackage" hidden/>
</div>
</div>
}
<div>
<button type="button" class="btn btn-danger px-2 btn-lg" onclick="PageBack(this.parentElement.parentElement)">Back</button>
<button type="button" class="btn btn-danger px-2 btn-lg" id="summary">Summary!</button>
</div>
</div>
Edit!!!!
i have changed this line in ajax now it start hitting my controller action but still all form values are empty seems model binding is unable to recognize my fields
**const model= $("form").serialize()**
console.log(model); //data is there thats fine
and in ajax
data: { model },
my model have field called packages which is list of some fields and inside it there is one another list.
One thing is clear. $("form").serialize() is not working in my case its giving me 415 Unsupported Media Type client error response. I think problem is due to nested List
I have checked your code on my side with a simple OrderViewModel object, it works well. I suggest you could try to add '[FromBody]' in the action method, Like this:
....
Edit
According your description, it seems that you are using the Nested List and meet 415 error when using the [FromBody]. I have modified the sample code, in the action method, it's not using the [FromBody] attribute and in the JQuery Ajax method, there is no need to use the JSON.stringify method to change the JavaScript object. More detail information, please check the following code:
Model Class (Suppose the OrderViewModel contain a List):
public class OrderViewModel
{
public int OrderId { get; set; }
public string OrderName { get; set; }
public List<Package> Packages { get; set; }
}
public class Package
{
public int Pid { get; set; }
public string PackageTitle { get; set; }
}
Code in the Controller:
/// <summary>
/// //display the order
/// </summary>
/// <returns></returns>
public IActionResult ShowOrder()
{
OrderViewModel ovm = new OrderViewModel()
{
OrderId = 1001,
OrderName = "order 1",
Packages = new List<Package>()
{
new Package(){ Pid=101, PackageTitle="first Package"},
new Package(){ Pid=102, PackageTitle="second package"}
}
};
return View(ovm);
}
/// <summary>
/// JQuery ajax post method
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
//...
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
ShowOrder.cshtml:
#model MVCSample.Models.OrderViewModel
#{
ViewData["Title"] = "ShowOrder";
}
<div class="row">
<div class="col-md-4">
<form asp-action="Showsummary" asp-controller="Home" method="post" class="signup-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrderId" class="control-label"></label>
<input asp-for="OrderId" class="form-control" />
<span asp-validation-for="OrderId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrderName" class="control-label"></label>
<input asp-for="OrderName" class="form-control" />
<span asp-validation-for="OrderName" class="text-danger"></span>
</div>
<div id="packages">
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="form-group">
<label asp-for="#Model.Packages[i].Pid" class="control-label"></label>
<input asp-for="#Model.Packages[i].Pid" class="form-control" />
<span asp-validation-for="#Model.Packages[i].Pid" class="text-danger"></span>
<br />
<label asp-for="#Model.Packages[i].PackageTitle" class="control-label"></label>
<input asp-for="#Model.Packages[i].PackageTitle" class="form-control" />
<span asp-validation-for="#Model.Packages[i].PackageTitle" class="text-danger"></span>
</div>
}
</div>
#*<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>*#
</form>
</div>
</div>
<div>
<input type="button" id="summary" value="Summary" />
<div id="page_3">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
//create a object to store the entered value.
var OrderViewModel = {};
//using jquery to get the entered value.
OrderViewModel.OrderId = $("input[name='OrderId']").val();
OrderViewModel.OrderName = $("input[name='OrderName']").val();
var packages = [];
//var count = $("#packages>.form-group").length; //you could use it to check the package count
$("#packages>.form-group").each(function (index, item) {
var package = {}
package.Pid = $(item).find("input[name='Packages[" + index + "].Pid']").val();
package.PackageTitle = $(item).find("input[name='Packages[" + index + "].PackageTitle']").val();
packages.push(package);
});
OrderViewModel.Packages = packages;
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: OrderViewModel,
success: function (data) {
console.log(data)
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Then the output as below:
Edit:
Besides, I also found that by using the above sample, if I just change the data: OrderViewModel to data: $("form.signup-form").serialize() (in the Ajax method), I could also get the OrderViewModel and the Packages in the action method.

Vue.js and Form array

I am converting a form from knockout to vue 2 with an ASP.NET MVC 5 Controller for the back end. This is my first attempt using vue. When the user presses the + button, it adds a new row onto the form. The issue I'm having is submitting that to the back end. The old knockout code dynamically set the name attribute in the form elements to Quantities so the form array properly submits all of the data. I would like to do the same thing with vue but am having a a bit of trouble dynamically setting the name of each element dynamically. What would be the best way to do this in order to submit the form without having to rewrite the Controller signature? It should store the form array under the name Quantities.
Image:
HTML:
<div id="radios" v-for="(row,key) in order">
<div class="row">
<div class="col-md-3">
#Html.SmartLabel("systemType", "System Type", true, labelClass)
<label>
<input type="radio" value="#Model.WifiId" v-model="order[key].selectedSystemType" v-on:change="systemChanged(key)"> Wifi
</label>
<label>
<input type="radio" value="#Model.WirelessId" v-model="order[key].selectedSystemType" v-on:change="systemChanged(key)"> Wireless
</label>
<label>
<input type="radio" value="#Model.FiberId" v-model="order[key].selectedSystemType" v-on:change="systemChanged(key)"> Fiber
</label>
</div>
<div class="col-md-4">
#Html.SmartLabel("assetType", "Asset Type", true, labelClass)
<!--
https://stackoverflow.com/questions/43812817/how-to-set-optgroup-select-label-in-vue-js
-->
<select id="asset-type" name="" class="form-control" v-model="order[key].selectedAsset" v-on:change="assetTypeChanged(key)">
<optgroup v-for="(group, name) in order[key].assets" v-bind:label="name">
<option v-for="asset in group" v-bind:value="asset">
{{asset.Name}}
</option>
</optgroup>
</select>
</div>
<div class="col-md-2">
#Html.SmartLabel("quantity", "Quantity", true, labelClass)
<input type="number" min="1" class="form-control" v-model="order[key].quantity" />
</div>
<div class="col-md-2">
<div v-show="costTracked">
#Html.SmartLabel("cost", "Unit Cost", true, labelClass)
<input type="number" min="1" class="form-control" v-model="order[key].cost" />
</div>
</div>
<div>
<span style="cursor:pointer" v-on:click="removeItem(key)">
X
</span>
</div>
</div>
</div>
Vue.js code:
var app = new Vue({
el: '#vue-app',
data: {
assets: {},
assetQuantityEnabled: false,
costTracked: false,
order: []
//Quantities: []
},
methods: {
// Trigger when system type radio selection changes
systemChanged: function (key) {
$.getJSON('#Url.Action( "GetAssetsOfSystem", "RadioOrder" )?systemTypeId=' + this.order[key].selectedSystemType, function (data) {
var result = {};
// Add assets to category (AssetCategory)
for (const asset of data) {
(asset.AssetCategoryName in result) ? result[asset.AssetCategoryName].push(asset) : result[asset.AssetCategoryName] = [];
}
// Sort assets within each category
for (const option in result) {
result[option].sort((a, b) => {
return a.Name.localeCompare(b.Name);
});
}
this.order[key].assets = result;
this.costTracked = false;
this.assetQuantityEnabled = false;
}.bind(this));
},
assetTypeChanged: function (key) {
this.assetQuantityEnabled = true;
this.costTracked = this.hasMacOrSerial(this.order[key].selectedAsset);
},
addItem: function () {
obj = this.defaultObj();
this.order.push(obj);
},
convertFormData: function(){
var q = [];
for(let i=0; i < this.order.length; i++)
{
var obj = {
AssetTypeId: this.order[i].selectedAsset.AssetTypeId,
AssetTypeIsSerialized: this.hasMacOrSerial(this.order[i].selectedAsset),
Quantity: this.order[i].quantity,
UnitCost: this.order[i].cost
};
q.push(obj);
}
return q;
},
defaultObj: function () {
return {
asset: '',
assets: [], // list items
cost: 0,
quantity: 1,
selectedSystemType: null,
selectedAsset: null
};
},
hasMacOrSerial: function (asset) {
return (asset.HasMacAddress || asset.HasSerialNumber) ? true : false;
},
removeItem: function (key) {
this.order.splice(key, 1);
}
}
});
Controller method signature:
public virtual ActionResult Create(
[Bind(Include = "VendorId,OrderNumber,RequisitionNumber,Quantities,SerializedAssets,Attempt")] InventoryOrderDto dto)
Old HTML using Knockout:
<div class="col-md-6">
<div class="panel panel-default white-box">
<div class="panel-heading">
<h3 class="panel-title">Order Summary</h3>
</div>
<div class="panel-body">
<div id="radios" data-bind="foreach: QuantitiesDisplay, visible: QuantitiesDisplay().length > 0" style="display: none">
<div class="row">
<input type="hidden" data-bind="value: AssetTypeId, attr: {name: 'Quantities[' + $index() + '].AssetTypeId'}" />
<input type="hidden" data-bind="value: AssetTypeIsSerialized, attr: {name: 'QuantitiesDisplay[' + $index() + '].AssetTypeIsSerialized'}" />
<input type="hidden" data-bind="value: UnitCost, attr: {name: 'Quantities[' + $index() + '].UnitCost'}" />
<div class="col-md-3" data-bind="text: AssetTypeName" style=" word-break: break-all;">
</div>
<div class="col-md-3">
<input type="number" min="1" class="form-control" data-bind="value: Quantity, attr: {name: 'Quantities[' + $index() + '].Quantity'}" />
</div>
<div class="col-md-3">
<input type="number" min="1" class="form-control" data-bind="visible:AssetTypeIsSerialized, value: UnitCost, attr: {name: 'Quantities[' + $index() + '].UnitCost'}" />
</div>
<div class="col-md-2">
<a class="btn btn-danger" title="Remove" data-bind="click: $root.removeItem">
<i class="fa fa-minus-circle"></i> Remove
</a>
</div>
</div>
</div>
<div id="emptyOrder" data-bind="visible: QuantitiesDisplay().length == 0">
No items are currently selected. Please choose from the adjacent pane.
</div>
<input id="submit" type="submit" value="Continue" class="btn btn-primary" data-bind="visible: QuantitiesDisplay().length > 0" style="display: none">
</div>
</div>
</div>
Ah I found it - need to use v-bind to dynamically set the name.
<div class="col-md-2">
#Html.SmartLabel("quantity", "Quantity", true, labelClass)
<input type="number" min="1" class="form-control" v-model="order[key].quantity" v-bind:name="'Quantities[' + key + '].Quantity' " />
</div>
https://medium.com/swlh/building-dynamic-forms-with-django-formsets-and-vue-js-f3c6e2dddd4a

How to check if a url belongs to a website that exists?

I am making a website where in a form, users can input a web page address. I was going to go with checking if the url is formatted correctly like an actual url which I think is the sloppy way and instead I want to check if url belongs to an actual website. Like, let's say user inputs www.pyrtyrmyrsyr.org, that is a valid address, but it doesn't lead to a website. Let's say user inputs www.python.org, that is both a valid address and leads to a website that exists.
And how can I check this validity before the form is sent and after input is given? Make the form's "send" button not clickable if url is not valid?
EDIT : Realized I didn't add any code of my view, apologize for that, also forgot to mention I use Bootstrap for View.
This is the form I use, what I am trying to do is use "Check" button, to check validity, by taking URL inside form-control with "id=url"
<div>
<div class="row">
<div class="col-md-12">
<h2 style="margin-left:20px; margin-top:10px">Add a Link</h2>
<form action="~/Link/Create" method="post">
<div class="form-group well clearfix" style="margin-left:20px; margin-right:20px; margin-top:20px">
<br />
<div class="row">
<label for="name" class="col-lg-2">URL:</label>
<div class="col-lg-9">
<input class="form-control" id="url" placeholder="URL" name="Address" /><br />
</div>
<div class="col-lg-1">
<button type="button" class="btn btn-primary" id="checkurl">Check</button>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<label for="name">Interval:</label>
</div>
<!--<div class="col-lg-10">
<input class="form-control" placeholder="Interval to check (minutes)" name="Interval" /><br />
</div>-->
<div class="col-lg-5">
<select class="form-control" id="sel1">
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
<option>Weeks</option>
<option>Months</option>
</select>
</div>
<div class="col-lg-5">
<select class="form-control" id="sel2">
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
<option>Weeks</option>
<option>Months</option>
</select>
</div>
</div>
<div class="row">
<button class="btn btn-success pull-right" type="submit" style="width:200px; margin-right:15px">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
As far as I searched so far, connection to another domain/website is not possible using Javascript or anything similar so I need a server-side language, so I need to take this url, send it to control and return a true/false value after checking connection.
You can use Remote Validation in Asp.NET MVC. Let you have following property in your model.
public string URL {get; set;}
Add Remote attribute to your property like
[Remote("YourAction", "YourController", HttpMethod = "GET", ErrorMessage = "URL is not valid.")]
public string URL {get; set;}
Now write the following code in your specified action of the controller.
public class YourController : Controller
{
[AllowAnonymous]
public ActionResult YourAction(string URL)
{
try
{
//Check here by hitting your URL using HTTPClient or WebClient that it is returning something or not.
WebClient wc = new WebClient();
string HTMLSource = wc.DownloadString(URL);
return Json(true, JsonRequestBehavior.AllowGet); //Return true if it is valid.
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet); //Return false if it is not vald.
}
}
}
You must have to add following configurations in your web.config
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Your code on view will be like
#Html.EditorFor(model => model.URL, new { type = "url", #class = "form-control", placeholder = "URL" } })
#Html.ValidationMessageFor(model => model.URL, "", new { #class = "text-danger" })
Solved it:
Added a bool to my model:
public bool Valid { get; set; }
Changed my view a little:
<div class="row">
<label for="name" class="col-lg-2">URL:</label>
<div class="col-lg-9">
<input class="form-control" id="url" placeholder="URL" name="Address" /><br />
</div>
<div class="col-lg-1">
<button type="button" class="btn btn-primary pull-right" id="checkurl">Check</button>
</div>
<input type="hidden" name="Valid" id="Validity"/>
</div>
Used the following codes, one for checking validity, other to reset form being usable if input is changed
$('#checkurl').click(function () {
var address = $('#url').val();
$.ajax({
url: "/Control/CheckUrl",
type: "POST",
data: JSON.stringify({ url: address }),
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result) {
document.getElementById("Validity").value = true;
document.getElementById("saveBut").disabled = false;
}
else {
document.getElementById("Validity").value = false;
document.getElementById("saveBut").disabled = true;
}
},
async: true,
processData: false
});
});
$('#url').change(function ()
{
if (document.getElementById("saveBut").disabled == false)
{
document.getElementById("Validity").value = false;
document.getElementById("saveBut").disabled = true;
}
});
Ajax code there leads to a controller function that reformats URL a bit and checks validity:
public ActionResult CheckUrl(string url)
{
try
{
if (String.IsNullOrEmpty(url)) return Json(false, JsonRequestBehavior.AllowGet); ;
if (url.Equals("about:blank")) return Json(false, JsonRequestBehavior.AllowGet); ;
if (!url.StartsWith("http://") && !url.StartsWith("https://"))
{
url = "http://" + url;
}
WebClient wc = new WebClient();
string HTMLSource = wc.DownloadString(url);
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
It works flawlessly and as desired.

How to add multiple fields in bootbox.prompt in mvc

I want to add a project name and task name while clicking on a particular date in fullcalendar but I don't know how to use bootbox.prompt or bootbox.dialog with more than one fields so can you help me out?
select: function (start, end, allDay) {
debugger;
bootbox.prompt("Add New Event", function (title) {
debugger;
if (title !== null) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay,
className: 'label-info'
},
true // make the event "stick"
);
}
});
It's quite simple, we can use bootbox dialog for that
bootbox.dialog({
title: 'Add New Event',
message: $('#form'),
show: false,
}).on("shown.bs.modal", function (e) {
$('#form').show()
}).on('hide.bs.modal', function (e) {
/**
* Bootbox will remove the modal (including the body which contains the login form)
* after hiding the modal
* Therefor, we need to backup the form
*/
$('#form').hide().appendTo('body');
})
.modal('show');
calendar.fullCalendar('unselect');
}
In html
<form id="form" method="post" class="form-horizontal" style="display: none;">
<div class="form-group">
<label class="col-xs-3 control-label">Username</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-primary" style="float:right;">Login</button>
</div>
</div>

Generate code for knockout binding for ASP.Net MVC

I have worked with knockout a little bit. It is a good client side data binding js library. A template is bound and populated on the client side as follows:
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Delete</legend>
<div class="display-label">
Student Id
</div>
<div class="display-field">
<input data-bind="value: StudentId" />
</div>
<div class="display-label">
First Name
</div>
<div class="display-field">
<input data-bind="value: FirstName" />
</div>
<div class="display-label">
Last Name
</div>
<div class="display-field">
<input data-bind="value: LastName" />
</div>
<div class="display-label">
Age
</div>
<div class="display-field">
<input data-bind="value: Age" />
</div>
</fieldset>
the above way we write html to bind data
this way populate template by js code
$(function () {
ko.applyBindings(StudentListVM);
StudentListVM.getStudents();
});
//View Model
var StudentListVM = {
Students: ko.observableArray([]),
getStudents: function () {
var self = this;
$.ajax({
type: "GET",
url: '/Student/FetchStudents',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.Students(data); //Put the response in ObservableArray
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
},
};
self.editStudent = function (student) {
window.location.href = '/Student/Edit/' + student.StudentId;
};
self.deleteStudent = function (student) {
window.location.href = '/Student/Delete/' + student.StudentId;
};
//Model
function Students(data) {
this.StudentId = ko.observable(data.StudentId);
this.FirstName = ko.observable(data.FirstName);
this.LastName = ko.observable(data.LastName);
}
The above code works and generates the UI on the client side.
I would like to know if there is any scaffolding option in MVC which generates the above html with binding expression and also generates the required js view model.
If this does not exist then I would appreciate suggestions on how to achieve it.
Take a look on Knockout mvc
You can write appropriate #helper method
Don't forget about T4
you can write your own extension for HtmlHelper

Resources