Viewbag not updating - c#

Currently on the I have some inline javascript, which makes an ajax call to a partial view controller which should have updated the viewbag along with it. However this does not seem to be the case, the data seems to persist from the main view which is null because it was never set there and if it was set then the data would still persist(tested).
Here is my javascript ajax call.
$.ajax({
url: btn.data('action-url'),
data: {
id: btn.data('id')
},
type: 'GET',
success: function (data) {
//delete all panels before showing new ones
$('.panel.panel-default').remove();
//push the new panels into the view
//$('#dash-content').html(data);
//Construct the partial view to be input into the main view
//Checks to see if browser supports templates
if ('content' in document.createElement('template')) {
var widgetModel = #Html.Raw(Json.Encode(ViewBag.widgets));
for (var i = 0; i < widgetModel.length; i++) {
var clone = loadwidgets(widgetModel[i]); //This function is in an external js file
var inputDestination = document.querySelector('#col2');
inputDestination.appendChild(clone);
console.log(inputDestination);
}
}
and here is the Action that it is calling.
public ActionResult Dashboard(int? id)
{
ModelState.Clear();
//get all widgets associated dashboard
var getWidgetsQuery = (from widgets in db.widgets
where widgets.DashID == id
select widgets);
ViewBag.widgets = getWidgetsQuery.ToList();
return PartialView();
}

Add an action to return the data i.e.
public ActionResult DashboardJson(int? id)
{
//get all widgets associated dashboard
var getWidgetsQuery = (from widgets in db.widgets
where widgets.DashID == id
select widgets);
var widgets = getWidgetsQuery;
return Json(widgets, JsonRequestBehavior.AllowGet);
}
Declare and serialize your model above the json call as you have done:
var widgetModel = #Html.Raw(Json.Encode(ViewBag.widgets));
Then within your success call simply re-assign it to the returned data:
widgetModel = data;

Related

executing mvc controller using either Jquery or Ajax call

I am trying to mimic an mvc ActionLink. I want the whole row to be clickable. when the actionlink is clicked, it calls the connected controller and executes the code within. I want my Jquery/ajax call to do the same.
I've tried multiple ways of doing this with no luck. I'm currently at a point where the row is clickable and the Jquery sees that, however the ajax call does not execute. Or, if it does, the controller does not execute correctly
Here is the Jquery code that catches the click.
$(document).ready(function () {
$('#policyTable').on('click', '.clickable-row', function (event) {
$(this).addClass('primary').siblings().removeClass('primary');
var Id = $(this).closest('tr').children('td:first').text();
var url = "/Home/ReviewPolicy";
var uc = $(this).closest('tr').children('td:first').text();
alert("Does the click work? " + Id);
$.ajax({
type: "POST",
url: "/Home/ReviewPolicy",
dataType: 'text',
data: { Id: Id }
});
})
})
Here is the controller it is calling:
[HttpPost]
public ActionResult ReviewPolicy(string Id)
{
//Declare policyVM for individual policy
PolicyRenewalListVM model;
int val = Convert.ToInt32(Id);
using (Db db = new Db())
{
//Get the row
PolicyRenewalListDTO dto = db.RenewalPolicies.Find(val);
//confirm policy exists
if (dto == null)
{
return Content("This policy cannot be found.");
}
//initialize the PolicyRenewalListVM
model = new PolicyRenewalListVM(dto);
}
//return view with model
return View(model);
}
When the actionlink itself is clicked (It's not here in the code as I didn't see it being necessary for this problem) it fires and everything works as it should, but the jquery call, sending the very same value (Id) does not.

How do I make this JOIN?

Im doing a college project with entity framework and i'm doing some JOIN's. I was doing well until I got to this JOIN that I don't know how to do.
Simplifying the functionality I have to implement: I have a button and when I click on it, it must show all the information from the tables, that's why I need to make the JOIN's, and I created a model for this purpose.
This is a screenshot of my SQL database:
SQL Database
And this is the code where I need to make the MetaEspecifica JOIN where the
foreign key is from AreaProcesso :
// GET: AreaProcesso/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var item = (from ap in db.AreaProcesso
join mg in db.MetaGenerica on ap.IdAreaProcesso equals mg.IdMetaGenerica
join model in db.Modelo on ap.IdAreaProcesso equals model.IdModelo
from nc in db.NivelCapacidade
from c in db.Categoria
from me in db.MetaEspecifica
where ap.IdAreaProcesso == id.Value
select new AreaProcessoModelView()
{
SiglaMetaGenerica = mg.Sigla,
NomeMetaGenerica = mg.Nome,
DescricaoMetaGenerica = mg.Descricao,
Sigla = ap.Sigla,
Nome = ap.Nome,
Descricao = ap.Descricao,
SiglaModelo = model.Sigla,
NomeModelo = model.Nome,
DescricaoModelo = model.Descricao,
SiglaNivelCapacidade = nc.Sigla,
NomeNivelCapacidade = nc.Nome,
DescricaoNivelCapacidade = nc.Descricao,
NomeCategoria = c.Nome
}).FirstOrDefault();
if (item == null)
{
return HttpNotFound(); // Or a return a view with message "item not found"
}
return View(item);
}
If you need have HTML page with JSON use this section under view page
#section Scripts {
var jsonData= #Html.Raw(Json.Encode(Model.YourDataCollection));
}
If you only need JSON data in the browser, change your controller and return Json like this:
return Json(item, JsonRequestBehavior.AllowGet);
Be careful if use return Json you say MVC this is not view page and only data serialization page
To view Details.cshtml file does not need a model, only after the design page layout only add this script in the script section
#section Scripts {
$.ajax({
dataType: 'json',
url: '#Url.Action("Details")',
type: 'GET',
cache: false,
success: function(result) {
// use json result
}
});
}

How to get selected index changed value in controller mvc c#

I am getting value in a dropdown list and I wanted to get the selected value in controller when user select any value from the dropdown list. My view is -
#using (Html.BeginForm("ApReport", "Sales", FormMethod.Post))
{
#Html.DropDownList("Ddl", null, "All", new { #class = "control-label"})
#Html.Hidden("rddl")
}
controller -
[HttpPost]
public ActionResult ApReport(ApReport Ddl)
{
string Ddlvalue = string.Empty;
if (Request.Form["rddl"] != null)
{
Ddlvalue = Request.Form["rddl"].ToString();
}
}
but I am not getting any value. Also, I donot want to use any submit button.
Thanks in advance
The use of Ajax allows you as the developer to update the main view without reloading the entire page, as well as send data to the server in the background.
This is how I would have accomplished this task.
Firstly, I would have created an action in my controller which returns a JsonResult. This will return a JSON object to your calling jquery code, that you can use to get values back into your views. Here is an example of the action method.
[HttpGet]
public JsonResult YourActionName(string selectedValue) //Assuming key in your dropdown is string
{
var result = DoYourCalculation(selectedValue);
return Json(new { myResult = result }, JsonRequestBehavior.AllowGet);
}
Now, you need to add your jquery code. I would recommend you place this in a seperate javascript file referenced by your view.
Here is the JQuery code, with the ajax call to the Action in your controller. The Ajax call to the server is initiated by the 'change' event of your DropDown, handled in JQuery, as can be seen below.
$(function () {
$(document)
.on('change', '#Ddl', function(){
var valueofDropDown = $(this).val();
var url = '/YourControllerName/YourActionName';
var dataToSend = { selectedValue: valueofDropDown }
$.ajax({
url: url,
data: dataToSend,
type: 'GET',
success: function (dataReceived) {
//update control on View
var receivedValue = dataReceived.myResult ;
$('YourControlIDToUpdate').val(receivedValue);
}
})
});
};

Binding data in created dropdown from ajax data

I have following dropdown created in cshtml page:
#( Html.Kendo().DropDownList().Name("ddlCode").OptionLabel("Select Code...").BindTo(#ViewBag.dropDown)
.DataTextField("Title")
.DataValueField("domainCode")
I am binding this dropdown on checking of oneof the checkbox on my page.
On checking of checkbox i have called javascript function and written ajax script as follows:
var ddl = $('#ddlCode').data("kendoDropDownList");
$.ajax({
url: "/PP/BindDropDown",
data: {
'Id': paramID
},
dataType: "json",
type: 'POST',
cache: false,
success: function (_data) {
ddl.dataSource.data(_data)
},
error: function () {
//
}
});
BindDropdown of PPController contains code as:
public JsonResult BindDropDown(string ID)
{
List<TEAMS_PP.Entity.correlations> list = new correlation().getDropDownvalues(ID);
ViewBag.dropDown = list;
return Json(list);
}
My problem is when dropdown gets bound it shows its items as "Undefined" as below:
How can i bind this dropdown???
I am using MVC4 Kendo UI Controls
Entity.Correlations:
public correlations() { }
public correlations(DB.EH_PP_DmainComp item)
{
//this.code = Convert.ToInt32( Convert.ToString(item.domainCode));
this.correlatedText = item.description;
this.codeTitle = item.title;
//Component 1a: Demonstrating Knowledge of Content and Pedagogy
//ArrayList arrCode = new ArrayList();
string[] arrCode = Convert.ToString(item.title).Split(':');
string[] code = Convert.ToString(arrCode[0]).Split(' ');
this.code = Convert.ToString(code[1]);
}
public DB.EH_PP_DmainComp ToDB()
{
var rec = new DB.EH_PP_DmainComp();
return rec;
}
public DB.EH_PP_DmainComp ToDB(DB.EH_PP_DmainComp rec)
{
return rec;
}
}
What's happening is that here...
#(Html.Kendo().DropDownList().Name("ddlCode").OptionLabel("Select Code...").BindTo(#ViewBag.dropDown)
.DataTextField("Title")
.DataValueField("domainCode")
You are telling the DropDownList to find the Title and the domainCode property in the correlations class. However, the correlations class does NOT have such properties.
To make this work you have to do one of the followings:
Add a Title and domainCode property to the correlations class
Use a different model object that exposes this property so that the dropdown list can bind to it

What should the MVC ActionResult return type be for an external HTML ajaxForm post

The idee is to post form data from a normal external Html page to another MVC site controller. Then the data is processed almost like using a webservice.
$(document).ready(function () {
var options = {
target: '#output',
success: function(data){ alert('test success'); },
url: http://localhost:57232/Services/SendFormData,
dataType: json
};
$('form').ajaxForm(options);
});
The ActionResult receives the data correctly in the FormCollection object.
[HttpPost]
public ActionResult SendFormData(FormCollection collection)
{
string s = string.Empty;
return Json(new { Success = true, Message = "Message!" }, JsonRequestBehavior.AllowGet);
}
At this point the success result is returned but when it gets to the external form my browser which is in this case IE tries to save or open the bytes returned instead of calling the success callback function.
Because this page is an external page, and not part of the MVC site I cannot use a View or Partial View. What should the return type be?
You need to return partialview result :
[HttpPost]
public ActionResult Form(Comment feedback)
{
if (feedback != null)
{
feedback.CommentedOn = DateTime.Now;
feedback.CommentId += 1;
if (ModelState.IsValid)
{
BlogPost blogpost = db.BlogPosts.Find(feedback.BlogId);
if (blogpost != null)
blogpost.NoofComments += 1;
db.Entry(blogpost).State = EntityState.Modified;
db.Entry(feedback).State = EntityState.Modified;
db.Comments.Add(feedback);
db.SaveChanges();
return PartialView("CommentSuccess", feedback);
}
}
return PartialView("Comment", feedback);
}
Also in the AjaxForm you need to set the UpdateTargetID:
#using (Ajax.BeginForm("Form", new AjaxOptions() { UpdateTargetId = "FormContainerdiv" , OnSuccess = "$.validator.unobtrusive.parse('form');", OnComplete = "OnComplete();" }))
in the targetId of the Ajax Form you need to mention the div id where you have to display the response data.
<div id="FormContainerdiv">.</div>
#Html.Partial("Comment", item);
</div>

Categories

Resources