How to pass model data in javascript
You can pass the model data into the java script file in these ways
(1). Just set the value in hidden field and access the value of hidden field in java script.
(2). And pass the value using function parameter.
(3).
var LoginResourceKeyCollection = {
UserName_Required: '<%= Model.UserName%>',
Password_Required: '<%= Model.Password%>'
}
</script>
Pass model data to javascript function
Your call to your JS function will look like this:
<a href="#" onclick="myFunction('@Model.id')"> </a>
This will send the current id
in concern to your JS function.
MVC Passing Model Data into JavaScript
I'd suggest you pass the list of numbers as a variable inside the scripts-section, instead of setting it as a data-attribute of the tag inside it. You can then use the variable in you script.
In your view:
@section scripts {
<script>
var mynumbers = "@string.Join(",", Model.numbers)";
</script>
<script id="script1" src="~/Scripts/render_sudoku.js" type="text/javascript"></script>
}
In your script:
var numbers = mynumbers.split(",");
for (var i in numbers)
{
var number = numbers[i];
// DO WHATEVER
}
Edit: You need to put the declaration of the Javascript variable inside quotes, or otherwise you will get an ESLint parsing error.
Passing asp.net mvc model into Javascript function
You need to convert Model.NextActionParam
to JSON string with Json.Encode()
method. Better way is put JSON inside <script>
section and set some variable, then use it anywhere.
<script>
var nextActionParam = @Html.Raw(Json.Encode(Model.NextActionParam));
</script>
<input type="button" id="btnNextAction" class="btn btn-primary" value="JSFunction"
onclick="callJS(nextActionParam)" />
Passing .net core model data to external javascript?
You can get C#/Razor values as a string easily enough.
<script type="text/javascript">
var i = parseInt('@Model.i');
</script>
Or you can try with below given options.
Option 1:
var myVar = '@Model.MyVar';
var name = '@Model.Name';
Option 2:
var myVar ='@Html.Raw(Model.MyVar)';
var name = '@Html.Raw(Model.Name)';
How to pass data object with list of objects to controller
For submitting complex models, you need to ensure that the name attribute of these controls bound to the Subcategory class fields are displayed in the form of a collection index.
And trigger the addSubCategory
click event in js to add Subcategory control and data.
Since you added model validation, I suggest you use ViewBag.Subcategories
to save the Subcategories data that has been added to the current page to prevent data loss after clicking the validation.
And you only need to add an asp-validation-summary in your form. Since these fields belong to a model and are in a form, their error information will be counted in the asp-validation-summary div.
Here is a complete example:
public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public List<Subcategory> Subcategories { get; set; }
}
public class Subcategory
{
[Required]
[DisplayName("Subcategory.Name")]
public string Name { get; set; }
}
Controller:
public IActionResult CreateCategory()
{
ViewBag.Subcategories = new List<Subcategory>() { };
return View();
}
[HttpPost]
public IActionResult CreateCategory(Category category)
{
if (!ModelState.IsValid)
{
// store Subcategories data which has been added
ViewBag.Subcategories = category.Subcategories == null ? new List<Subcategory>() { } : category.Subcategories;
return View("CreateCategory");
}
_categoriesRepository.AddCategory(category);
return RedirectToAction("ManageCategories");
}
View:
@model AplikacjaFryzjer_v2.Models.Category
@{
ViewData["Title"] = "Dodaj nową kategorię";
Layout = "~/Views/Shared/_Layout.cshtml";
var SubcategoriesData = (IList<AplikacjaFryzjer_v2.Models.Subcategory>)ViewBag.Subcategories;
}
<h1>Dodaj nową kategorię</h1>
<form method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Dodaj kategorię</button>
</div>
<div class="col-md-6 offset-6">
@for (int i = 0; i < SubcategoriesData.Count(); i++)
{
<div class="form-group">
<label>Name@(i)</label>
<input asp-for="Subcategories[i].Name" value="@SubcategoriesData[i].Name" />
<span asp-validation-for="Subcategories[i].Name" class="text-danger"></span>
</div>
}
<button class="btn btn-primary" onclick="RemoveSubcategory(this)" id="removeSubcategory">remove</button>
<button class="btn btn-primary" id="addSubCategory" value="table">Dodaj podkategorię</button>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
</div>
</form>
@section Scripts
{
<script>
var i = @SubcategoriesData.Count()-1;
$(document).ready(function () {
if (@SubcategoriesData.Count() <= 0) {
$("#removeSubcategory").hide();
}
$("#addSubCategory").click(function (e) {
e.preventDefault();
i++;
var name = '<label>Name' + i + '</label><input name = "Subcategories[' + i + '].Name" type="text"/>';
$("#removeSubcategory").before('<div class="form-group">' + name + '</div>');
$("#removeSubcategory").show();
});
});
function RemoveSubcategory(btn) {
event.preventDefault();
$(btn).prev("div").remove();
i--;
if (i == @SubcategoriesData.Count() -1) {
$("#removeSubcategory").hide();
}
}
</script>
}
Here is test result:
How to pass model object to javascript function in asp.net Core
I have solved this problem!Solution:
Model:
public class SalesViewModel
{
public string salesdate { get; set; }
public int salesprice { get; set; }
}
Data:
public class SalesContext
{
public string ConnectionString { get; set; }
public SalesContext(string connectionString)
{
this.ConnectionString = connectionString;
}
public SalesContext()
{
}
public List<SalesViewModel> GetAllData()
{
List<SalesViewModel> list = new List<SalesViewModel>();
list.Add(new SalesViewModel() { salesdate = "1", salesprice = 3 });
list.Add(new SalesViewModel() { salesdate = "2", salesprice = 6 });
list.Add(new SalesViewModel() { salesdate = "3", salesprice = 7 });
list.Add(new SalesViewModel() { salesdate = "4", salesprice = 2 });
list.Add(new SalesViewModel() { salesdate = "5", salesprice = 1 });
return list;
}
}
Controller:
using Newtonsoft.Json;
public IActionResult Chart()
{
SalesContext sc = new SalesContext();
string json = JsonConvert.SerializeObject(sc.GetAllData());
//ViewData["chart"] = json;
ViewBag.Sales = json;
return View(sc.GetAllData());
}
View:
document.getElementById('addData').addEventListener('click', function() {
if (config.data.datasets.length > 0) {
var salesdata = @Html.Raw(ViewBag.Sales);
config.data.datasets.forEach(function(dataset) {
for (var i = 0; i < salesdata.length; i++) {
var month = MONTHS[config.data.labels.length % MONTHS.length];
config.data.labels.push(month);
dataset.data.push(salesdata[i].salesprice);
}
});
window.myLine.update();
}
});
use var salesdata = @Html.Raw(ViewBag.Sales)
to get data from controller!
use salesdata[i].salesprice
to push data to the dataset!
Thanks!
Related Topics
How to Refresh Form Page After Post Request
How to Reload Datatables from Another Ajax Request With Onclick
Trouble Converting Dates String to Yyyy-Mm-Ddthh:Mm:Ss-Hh:Mm Format
Jquery Validation Code for Not Allowed Only Blank Space in Textbox
Regex Pattern to Match At Least 1 Number and 1 Character in a String
How to Remove All Null and Empty String Values from an Object
How to Change the Font Color, Font Size, and Button Color in React
How to Trigger Change of Option in Dropdown When Options Can Have Same Value
How to Add a New Object (Key-Value Pair) to an Array in JavaScript
React - How to Add Dynamic Key/Value Pair to an Object
Regex in JavaScript Allow Only Numbers and One Dot Followed by Max 2 Number
Onclick Button Get from Database and Display on a Input Field Live
How Get Total Sum from Input Box Values Using JavaScript
Random Numbers Between 1 and 50; 50 Times
How to Cancel Ongoing Http Requests When There's a New Requests in Angular 6 With Rxjs 6
Prevent React-Router History.Push from Reloading Current Route