How to pass model from partialView to javascript in asp.net mvc - javascript

I wanna pass down model from partialView to javascript and process it in controller,
now the problem is i couldn't pass the model where when i run the code it show null. can anyone help me on this?
*HTML code
#model List<TPMS.Models.Draft_SingleValue>
<div class="row">
<div class="col-lg-12">
<table class="table table-bordered">
<thead>
<tr class="bg-gray">
<th>Keyword</th>
<th>Default Value <span class="pull-right"><i class="fa fa-edit"></i></span></th>
<th><span class="pull-right"><i></i></span></th>
</tr>
</thead>
<tbody>
#foreach (var sdata in Model.OrderBy(i => i.Keyword))
{
<tr id="#sdata.DraftSingleValue_ID">
<td id="sv:#sdata.DraftSingleValue_ID:Keyword" contenteditable="false">#sdata.Keyword</td>
<td id="sv:#sdata.DraftSingleValue_ID:Default_Value" contenteditable="false"> #sdata.Default_Value</td>
<td id="sv:#sdata.DraftSingleValue_ID" contenteditable="false" class="">
<span class="btn-group center-block" id="PlusButton">
<a class="btn btn-success btn-xs" href="javascript:AddKeyword('#sdata');" data-id="#sdata"><i class="fa fa-plus"></i> </a>
</span>
</td>
</tr>
}
</tbody>
<tfoot>
<tr class="bg-gray">
<th>Keyword</th>
<th>Default_Value <span class="pull-right"><i class="fa fa-edit"></i></span></th>
<th><span class="pull-right"><i></i></span></th>
</tr>
</tfoot>
</table>
</div>
</div>
*Javascript
function AddKeyword(SvModel) {
debugger
//var model = $('#Testing').attr('data-id');
$.ajax({
url: "#Url.Action("AddSingleValue", "Draft")",
cache: false,
type: "GET",
datatype: 'html',
data: {"Model": SvModel },
success: function (data) {
$('#List_Keyword').modal('hide');
$("#List_SVKeywords").html(data);
$('#List_Keyword').modal('show');
},
error: function () {
alert('Failed to retrieve values.');
document.getElementById("del_err_span_dialog").innerHTML = "Fatal Error, Please try again.";
}
});
}
*Controller
public ActionResult AddSingleValue(Draft_SingleValue Model)
{
Draft_SingleValue svmodel = new Draft_SingleValue();
svmodel.Draft_File_ID = Model.Draft_File_ID;
svmodel.Data_Type = Model.Data_Type;
svmodel.Group_Name = Model.Group_Name;
svmodel.Is_Active = Model.Is_Active;
svmodel.Keyword = Model.Keyword;
svmodel.Max_Length = Model.Max_Length;
svmodel.Min_Length = Model.Min_Length;
svmodel.Modified_By = User.Identity.Name;
svmodel.Modified_On = DateTime.Now;
svmodel.Remarks = Model.Remarks;
svmodel.Default_Value = Model.Default_Value;
_temporaryrepo.Insert_TemporarySingleValue(svmodel);
return ListSv(svmodel.Draft_File_ID);
//return new EmptyResult();
}
As you guys can c from above code, im trying to pass model to AddKeyword function but i cant. it will be great if anyone can show me a way to do this.

Try this:
View:
#using (Html.BeginForm("YourActionMethod", "YourController", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
//code omitted for brevity
}
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("YourActionMethod", "YourController")',
data: formdata, //! your model data
dataType: "json",
success: function (response) {
if (response.success) {
//success
}
else {
//error
}
}
});
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult YourActionMethod([Bind(Exclude = null)] Model viewModel)
{
//...
return Json(new { success = true, message = "Success!.." },
JsonRequestBehavior.AllowGet);
}

Related

Get ID on click of a button AJAX way

I am building a small application using ASP.NET MVC Core 3.1.
I am displaying few buttons on the View. Each row has a button. When a button is clicked corresponding to a row, I want to get the ID value of this row but without page refresh. It should be done using AJAX.
The View code is something like this:
#using Updater.Models
#model IEnumerable<TemplateData>
#{
Layout = null;
}
#{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
#if (Model.Count() > 0)
{
<hr />
<table cellpadding="0" cellspacing="0" border="1" style="height:600px">
<tr>
<th>ID</th>
<th>Location</th>
<th>Observation Type</th>
<th>EmpName</th>
<th>Status</th>
</tr>
#foreach (TemplateData sheet in Model)
{
<tr>
<td>#sheet.ID</td>
<td>#sheet.Location</td>
<td>#sheet.ObservationType</td>
<td>#sheet.EmpName</td>
<td>
#Html.DropDownList("CI Status", new List<SelectListItem>
{
new SelectListItem{ Text="", Value = "0" },
new SelectListItem{ Text="Completed", Value = "1" },
new SelectListItem{ Text="In-Progress", Value = "2" },
new SelectListItem{ Text="Review", Value = "3" },
})
</td>
</tr>
<tr>
<td>
#using (Html.BeginForm("Index", "sheet", FormMethod.Post))
{
<input type="submit" value="Update Status" class="ids" data-id="#sheet.ID" />
}
</td>
</tr>
}
</table>
}
</div>
<script type="text/javascript">
$('.ids').click(function() {
var rowID = $(this).data('id');
alert(rowID);
});
</script>
** Edited **
In continuation of what Costa suggested below to call controller from Javascript, I attempted below code, but instead of showing message, it is directing to URL: http://localhost/sheet
<tr>
<td>
#using (Html.BeginForm("Index", "sheet", FormMethod.Post))
{
<input type="submit" id="btnSubmit" value="Update Status" class="ids" data-id="#sheet.ID" onClick="UpdateStatus(#sheet.ID)"/>
}
</td>
</tr>
}
</table>
}
</div>
<script type="text/javascript">
$.ajax({
type: "POST",
url: '#Url.Action("Home", "UpdateStatus")',
contentType: "application/json; charset=utf-8",
data: id,
dataType: "json",
success: function() { alert('Success'); },
error: function() { alert('Error'); }
});
</script>
Controller Code
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[HttpPost]
[Route("UpdateStatus")]
public void UpdateStatus()
{
//Do Something
}
}
If you want to pass the ID to javascript, you can use this:
<input type="submit" value="Update Status" class="ids" data-id="#sheet.ID" onClick="UpdateStatus(#sheet.ID)" />
<script>
function UpdateStatus(string id) {
$.ajax({
type: "POST",
url: "/UpdateStatus",
contentType: "application/json; charset=utf-8",
data: {"id": id},
dataType: "json",
success: function() { alert('Success'); },
error: function() { alert('Error'); }
});
}
</script>
Finally, edit your controller like this:
[HttpPost]
[Route("UpdateStatus/{id}")]
public void UpdateStatus(string id)
{
//Do Something
}

Display Information from LINQ query

So I have a string that has been passed from JS to my controller like so:
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("getCounty", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
});
}
Controller
[HttpPost]
public ActionResult Index([FromBody] string userCounty)
{
var county = userCounty.Substring(0, userCounty.IndexOf(" "));
var query = from m in _context.model where m.county == county select new Model
{
FirstName = m.Firstname
LastName = m.LastName
};
if (query == null)
{
return NotFound();
}
return View(query.ToList());
}
[HttpGet]
public ActionResult Index()
{
return View();
}
View
#model Project.Models.ModelName
<table class="table">
<tbody>
<tr>
<td>
#Html.DisplayFor(model => model.FirstName) #Html.DisplayFor(model => model.LastName)
</td>
</tr>
</tbody>
I am able to pass the string from JS to my controller and query the database but how do I update the page to show the results of the query in my view? Anything helps. Thank you!
The data returned by ajax is text or json. If you want to use c# to update the page. You can make action getCounty return partial view, partial view automatically returns data with html.
Change action getCounty.
[HttpPost("getCounty")]
public ActionResult Index([FromBody] string userCounty)
{
var county = userCounty.Substring(0, userCounty.IndexOf(" "));
//...
return PartialView(query.ToList());
}
PartialView Index.cshtml
#model List<ModelName>
<table class="table">
<tbody>
#for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model[i].FirstName) #Html.DisplayFor(model => model[i].LastName)
</td>
</tr>
}
</tbody>
</table>
View
#model ModelName
<div id="datalist">
</div>
<!--other code-->
#section Scripts{
<script>
function findEmployees(userCounty) {
$.ajax({
type: "POST",
//dataType: "json",
url: '#Url.Action("getCounty", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (data) {
$('#datalist').html(data)
},
error: function (e) {
console.log(e)
}
});
}
</script>
}
It can generate different data tables according to userCounty
You can get the list to the page like this.You can then press inside a div or ul list with each loop.
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("getCounty", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (result) {
if (result.data.length !== 0) {
$.each(result.data, function (index, value) {
var firstName = value.firstName;
var lastName = value.lastName;
});
}
},
});
}

Ajax call returning null model when using form inside data table?

I have a bootstrap form inside data-table and i am updating one input filed in this form actually there are multiple input fields and when I press submit button if any new data is entered in fields it will be updated in the database I am using ajax call for sending the data but as we know there are multiple pages in data-table so at the first page data is submitted successfully but on the other pages ajax call sending null model to the controller which cause null data exception.
<form id="share">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="container col-md-12">
<table id="myTable" class="table table-hover table-striped table-bordered dataTable">
<thead>
<tr>
<th style="text-align:center">#Html.DisplayNameFor(m => Model.tags.First().Id)</th>
<th style="text-align:center">#Html.DisplayNameFor(m => Model.tags.First().TagName)</th>
<th style="text-align:center">#Html.DisplayNameFor(m => Model.tags.First().TagCategory)</th>
<th style="text-align:center">#Html.DisplayNameFor(m => Model.tags.First().TagValue)</th>
<th style="text-align:center"> Action</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.tags.Count(); i++)
{
<tr>
<td>
#Html.DisplayFor(m => Model.tags[i].Id)
#Html.HiddenFor(m => Model.tags[i].Id)
</td>
<td>
#Html.DisplayFor(m => Model.tags[i].TagName)
</td>
<td>
#Html.DisplayFor(m => Model.tags[i].TagCategory)
</td>
<td>
#Html.EditorFor(m => Model.tags[i].TagValue, new { htmlAttributes = new { #id = "TagVaule_" + Model.tags[i].Id, #class = "form-control" } })
#Html.ValidationMessageFor(m => Model.tags[i].TagValue, "", new { #class = "text-danger" })
</td>
<td>
#if (User.IsInRole("Admin"))
{
<button type="button" class="btn btn-danger" onclick="UpdateRow(#Model.tags[i].Id)">Update</button>
}
else
{
<button type="button" class="btn btn-danger" onclick="UpdateRow(#Model.tags[i].Id)" disabled>Update</button>
}
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content" id="myModalContent">
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-10">
#if (User.IsInRole("Admin"))
{
<button type="button" class="btn btn-danger" id="bulkupdate">BulkUpdate</button>
}
else
{
<button type="button" class="btn btn-danger" id="bulkupdate" disabled>BulkUpdate</button>
}
</div>
</div>
</div>
#section Scripts{
<script>
$(document).ready(function () {
$('#myTable').DataTable({
'columns': [
null,
null,
null,
{ "width": "20%" },
null
],
});
});
var form = $("#share");
$(document).on('click', '#bulkupdate',function () {
debugger;
$.ajax({
type: 'GET',
url: '#Url.Action("BulkUpdate", "Home")',
data: form.serialize(),
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
});
//BulkUpdate Confirmation
function BulkConfirm()
{
var form= $("#share");
$.ajax({
type: 'POST', //GET
url: '#Url.Action("BulkUpdateConfirmation", "Home")',
data: form.serialize()
});
$("#myModal").modal('hide')
}
//Single row update
var RowId = 0;
var tagvalue = 0;
function UpdateRow(id)
{
tagvalue = $("#TagVaule_" + id).val();
RowId = id;
DisplayModal();
}
function DisplayModal()
{
$.ajax({
type: "GET",
url: '#Url.Action("Update","Home")',
data: {
id: RowId,
value: tagvalue
},
success: function(data)
{
$('#myModalContent').html(data);
$('#myModal').modal('show');
},
});
}
function Confirm()
{
$.ajax({
type: "POST",
url: '#Url.Action("SaveUpdate","Home")',
data: {
id: RowId,
value: tagvalue
},
});
$("#myModal").modal('hide')
}
</script>
}
//Controller Code
public ActionResult BulkUpdate(List<Tag> tags)
{
foreach (var item in tags)
{
if (item.TagValue == null || Regex.Matches(item.TagValue.ToString(), #"[a-zA-Z]").Count > 0)
{
return PartialView("_InvalidModel");
}
}
if (ModelState.IsValid)
{
obj.updatedDatas = new List<UpdatedData>();
foreach (var item in tags)
{
var tag = db.Tags.Where(x => x.Id.Equals(item.Id)).FirstOrDefault();
if (tag.TagValue != item.TagValue)
{
UpdatedData changedRow = new UpdatedData
{
OldTagValue = tag.TagValue,
NewTagValue = item.TagValue,
TagName = tag.TagName
};
obj.updatedDatas.Add(changedRow);
}
}
}
return PartialView("_UpdateConfirmationBulk", obj);
}
I am updating the form in two ways one is single row update and the other is multiple row updates or bulk update I am facing this issue in bulk update as in bulk update user changes the values of as many inputs as he want (also from other pages) and press the bulk update button to submit all the changes at a time.

How to pass the id in vue js for the post ajax request?

I need to pass an "id" obtained as data in vue js? I am getting id as "agnt.basic.actor". Since there are many id's present, how can i able to pass the same
<tr v-for="agnt in agentlist">
<td v-if="agnt.basic">{{agnt.basic.actor}}</td>
<td v-if="agnt.basic">{{agnt.basic.name}}</td>
<td v-if="agnt.basic">{{agnt.basic.email}}</td>
<td v-if="agnt.basic">{{agnt.basic.phone}}</td>
<td v-if="agnt.basic"><a v-bind:href="'/agentpendingdetails/'+agnt.basic.actor">Basic Details</a></td>
<td> <form method="POST" v-on:submit.prevent="handelSubmit();">
<div class="text-center">
<button type="submit" class="btn btn-info btn-fill btn-wd"><a v-bind:value="agnt.basic.actor"> Verify</a></button>
</div>
<div class="clearfix"></div>
</form></td>
</tr>
When I click on submit button i need to pass the id obtained from "agnt.basic.actor".
How can I able to implement the same? Please help me.
My vue js code is
<script>
dash = new Vue({
el: '#dash',
data: {
agentlist: {
basic: [],
},
authType: '{{ uid }}',
id: '',
},
mounted() {
var self = this;
data = {};
data['auth-token'] = this.authType;
$.ajax({
url: "http://alpha/admin/get/agents/pending/",
data: data,
type: "POST",
dataType: 'json',
success: function (e) {
if (e.status == 1) {
self.agentlist = e.data
}
},
});
},
methods: {
handelSubmit: function (e) {
var vm = this;
data = {};
data['auth-token'] = this.authType;
data['uid'] = this.uid;
$.ajax({
url: 'http://127.0.0.1:8000/alpha/admin/verify/user/',
data: data,
type: "POST",
dataType: 'json',
success: function (e) {
if (e.status) {
vm.pid = e.pid;
console.log(vm.pid);
}
else {
vm.response = e;
}
}
});
return false;
},
},
})
</script>
So, how can I able to pass the id? Please help me to obatain the result.
Instead of using form tag just use a normal button to submit the form and pass the current agnt data to submit function.
So your HTML Should be
<tr v-for="agnt in agentlist">
<td v-if="agnt.basic">{{agnt.basic.actor}}</td>
<td v-if="agnt.basic">{{agnt.basic.name}}</td>
<td v-if="agnt.basic">{{agnt.basic.email}}</td>
<td v-if="agnt.basic">{{agnt.basic.phone}}</td>
<td v-if="agnt.basic"><a :href="'/agentpendingdetails/'+agnt.basic.actor">Basic Details</a></td>
<td>
<button #click="handleSubmit(agnt)" class="btn btn-info btn-fill btn-wd">Verify</button>
</td>
</tr>
and method should be,
handleSubmit: function (agnt) {
var vm = this;
data = {};
data['auth-token'] = this.authType;
data['uid'] = this.uid;
data['agent-actor'] = agnt.basic.actor
$.ajax({
url: 'http://127.0.0.1:8000/alpha/admin/verify/user/',
data: data,
type: "POST",
dataType: 'json',
success: function (e) {
if (e.status) {
vm.pid = e.pid;
console.log(vm.pid);
} else {
vm.response = e;
}
}
});
return false;

model not passing to controller from view

I am new to mvc and javascript.At first I am using javascript to appned the parital view in divsion
$('.btngo').click(function (e) {
var fid = $('#FiscalYear_FYId').val();
alert($('#FiscalYear_FYId').val());
$.ajax({
type: 'Get',
url: '#Url.Action("RateList", "Rate")',
data: { fyid: fid },
success: function (sc) {
$('#Ratelist').html(sc);
}
});
});
The partial view is of model FHIControl.Model.StationeryRate.RateDTO which consists a submit button my view looks like
#using (Html.BeginForm("Ratelist", "Rate", FormMethod.Post))
{
#Html.ValidationSummary(true)
<table>
<thead>
<tr>
<th>Item Id</th>
<th>Item Name</th>
<th>Rate</th>
</tr>
</thead>
#Html.HiddenFor(x=>Model.FiscalYear.FYId)
#foreach (var item in Model.RateList)
{
<tr>
#Html.HiddenFor(x => item.ItemId)
<td>#{count++;}#count</td>
<td>#Html.DisplayFor(x => item.ItemName)</td>
<td>#Html.TextBoxFor(x => item.Rate)</td>
</tr>
}
</table>
<p>
<input type="submit" value="Ok" id="btnsubmit" />
</p>
}
The button submit is submiting the form but there is no model items.Why is it so?Is there any way to make this work?
There is no model items because you are only passing the value of FiscalYear_FYId:
var fid = $('#FiscalYear_FYId').val();
$.ajax({
data: { fyid: fid },
});
which should be:
$.ajax({
data: $form.serialize(),
});
where $form is a reference to your form. That you can either give a name for faster and better reference, or you can reference it like this:
var $form = $("#btnsubmit").parents('form');

Categories