MVC ViewData not rendering in View - asp.net

I have the following code in my post action method for Edit.
JobCardService.Update(viewData.JobCard);
var js = new JavaScriptSerializer();
ViewData["Notifications"] = js.Serialize(new {NoteificationType = "Success", Message = "The installtion was successfully updated"});
return RedirectToAction("Index");
However, on the client, ViewData is null/empty, i.e. this client code
var notifications = eval("<%= ViewData["Notifications"]%>");
renders as
var notifications = eval("");
I'm sure I'm doing something small wrong.

ProfK - I think (as you'll no doubt be aware) you'll have to parse that json result in javascript once you get into your index view via the redirect. the jquery .getJson() method would seem most appropriate: http://api.jquery.com/jQuery.getJSON/
Also, as you're doing a RedirectToAction, then the context of the ViewData will be lost. In that case, you want to use TempData as a drop in replacement. Below is an example of what you could try:
jim
[edit] - not sure if this would work:
// in the controller
TempData["Notifications"] = js.Serialize(...);
// in the index view
function getMyJsondata() {
var json = $.getJson('<%=ViewContext.TempData["Notifications"] %>');
}
or as per your amendment to the question, try this:
// alternative in index view
eval("(" + "<%= TempData['Notifications']%>" + ")");
give it a go...
adendum:
to quote from a previous SO question on Tempdata vs ViewData: What is TempData collection used for in asp.net MVC?
TempData is used to share data between
controller actions. If your controller
does a RedirectToAction and the target
action needs data (perhaps a
particular model instance) to act
upon, you can store this data in
TempData. Using TempData is similar to
storing it in the session, but only
for one round-trip. You use TempData
when you need to pass data to another
controller action rather than a view
for rendering.

Related

Create a url that passes values to controller action

I want to create a Url that I can email that goes to an action within a controller, passing to the action an Id and a Token. This is my code so far:
var action = new UrlActionContext
{
Action = "Verify",
Controller = "Auth",
Values = id, token
};
var url = UrlHelperExtensions.Action(action);
UrlHelperExtensions.Action is expecting an IUrlHelper however, and I have not been able to get this to work using that interface. Can someone please explain how I am able to form a Url that goes to this action?
I can only seem to find solutions to Asp.Net MVC projects, whereas I am using Asp.Net Core 2.0.
For ASP.Net Core 2.0 IUrlHelper is available as a property of the controller. ControllerBase.Url is an IUrlHelper instance. You should be using it like this:
var url = Url.Action(nameof(DoSomething), new { id = 10 });

recovering from missing session state in ASP.NET MVC with Telerik Ajax

I have a webpage which includes a telerik grid in ajax mode. The data for the grid is constructed in the controller action used to serve the view, and then stored in the session. 90% of the time its available to the ajax method used to populate the grid. And sometimes its not, which is odd. Some sort of race condition ?
public ActionResult EditImage(int productModelId, int revision)
{
ViewBag.Current = "Edit";
//Unit of work and repo generation removed from brevity
var modelToEdit = prodModelRepo.Where(p => p.ProductModelID == productModelId && p.Revision == revision).FirstOrDefault();
var vmie = new VMImageEdit(modelToEdit)
{
//init some other stuff
};
Session["vmie"] = vmie;
return View(vmie);
}
Now the telerik contorol will post back to _EISelect in order to populate its grid
// Ajax Actions for EditImage
[GridAction]
public ActionResult _EISelect()
{
var vmie = (VMImageEdit) Session["vmie"];
return View(new GridModel(vmie.Colours));
}
So if my session object is null, how can I recover - I guess I need the productModelId and Revision parameters from the original EditImage call. Are they available in the _EISelect in any way - its posted to, and the post contains nothing useful.
Oh to make this possibly harder, this page will be displayed via an inline frame.
The answer lies in the telerik ajax databinding - this can be used to pass arbitrary data in the querystring
.Select("_EISelect", "AdminProduct", new { productModelId = Model.ProductModelId, revision = Model.Revision})
which can be recovered in _EISelect as parameters. Simples.

Find a control by String from asp.net Web service

Well since it seems relatively difficult to send the object of a WebControl over JSON using jquery.ajax() I've decided to send the name of the control as a string because I know how to do that. Then I promptly realized that, from a web service, I don't actually know how to search for a control by ID name. Since its a service I can't seem to get Control.FindControl() to work so does anyone have ideas or suggestions? All I'm trying to do is call a databind() on my radcombobox.
Thanks in advance!
For any of you that knows anything about asp.net/rad controls - I'm basically updating a database and want the radcombobox to be in sync with that database again after adding something, before I autoselect what was just added. Other than databind do i have to call anything to refresh that list?
Thanks again!
The way i would go in this case is the following:
Make some change on the data set
Make a call to the web service to update the html page
On the service method - i would load the same control and data bind it with the updated data set like this:
// create standard webform
Page page = new Page();
HtmlForm form = new HtmlForm();
page.Controls.Add(form);
// prepare for rendering
StringBuilder html = new StringBuilder();
StringWriter tw = new StringWriter(html);
HtmlTextWriter hw = new HtmlTextWriter(tw);
// load the control to render
Control control = page.LoadControl("relativeControlPath");
TypeOfYourControl myControl = (TypeOfYourControl)control;
myControl.DataSet = GetUpdatedDataSet();
myControl.DataBind();
form.Controls.Add(myControl);
// render
HttpContext.Current.Server.Execute(page, hw, false);
// pack the output as JSON
result.Add("html", html.ToString());
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(result);
return json;
4. When the ajax call receives a response from the previous step, all i have to do i s to replace the current dom element with the newly rendered one:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "webServiceUrl",
data: "{'if you need a specific params to identify nature of your control':'" + data + "'}",
dataType: 'json',
success: function(result) {
var output = eval('(' + result.d + ')');
$("oldNode").remove();
$("parentNode").append(output.html);
}
});
This approach is generally suitable when you are dealing with composite controls and cannot control or change their behavior.
But for general async update methods i would recommend more lightweight methods like sending serialized data over JSON and using something like jQuery templates on client side for markup generation.

Passing flash variables to asp.net

I don't know much about Flash but we are working on a site that has a flash form and when the users pick an option, like selecting a value from a drop down list, we need the value to be passed to asp.net server-side code. What's the easiest way to do this?
Flash can invoke server side service. So use GET or POST to pass data
You could explore these options:
1) Communicate between the SWF and the containing page through JavaScript
2) Communicate via asp.net webservices from the SWF directly to the webservice.
3) Not sure but could probably do a POST to a processing aspx page?
HTH
I think a good option is to use the XML class so consider this:
var xmlRequest = new XML();
xmlRequest.onLoad = parseXMLResponse;
xmlRequest.load("http://yourpathtoyourserver/file.aspx?listselectedvalue=something");
function parseXMLRequest(loaded)
{
trace("hi");
}
You can also have the page give you data back this way so it's not just one way communication.
Assuming you are using Action Script 2.
Read the important notes at the bottom of each codes pertain to sending and retrieving data from flash to .net page. Explanation of the code is in the comment inside the code.
Flash Part (Action Script 2)
//function to send collected form data to asp.net page
//use other control/button to call this function
//important: in order for the 'onLoad' event to work correctly, this function has to be 'Void'
function sendForm():Void
{
//create LoadVars object
var lv_in:LoadVars = new LoadVars();
var lv_out:LoadVars = new LoadVars();
//set onLoad event
lv_in.onLoad = function(success:Boolean)
{
//if success, meaning data has received from .net page, run this code
if (success)
{
//lv_in.status is use to get the posted data from .Net page
statusMsg.text = "Thank you for filling up the form!" + lv_in.status;
}
//if fail, run this code
else
{
statusMsg.text = "The form you are trying to fill up has an error!";
}
}
//this is the collected data from the form
lv_out.userName = txtUserName.text;
lv_out.userAddress = txtUserAddress.text;
lv_out.userBirthday = txtUserBirthday.text;
//begin invoke .net page
lv_out.sendAndLoad("ProcessDataForm.aspx", lv_in, "POST");
}
Important note:
The function that contain onLoad event, in this case sendForm function, has to be Void function, meaning it's not returning value. If this function return value, what happen is the function will be executed all the way without waiting for the returned data from .net page, thus the onLoad event will not be set properly.
.Net Part
public void ProcessData
{
//process the data here
Response.Write("status=processed&");
}
Important note:
To send data/message back to flash, you can use Response.Write. However, if you want Action Script to parse the posted message/data from .Net page keep in mind you have to include & symbol at the end of the message. When parsing data/message, Action Script will stop at & symbol, thus leave the rest of the message alone and only get the message under sent variable.

ASP NET MVC Server Response to a basic ajax request

We have to make an ASP.NET MVC or ASP.NET application for basic ajax navigation in Customer.html of Notrhwind.mdb.
We have this 3 things:
A pure HTML/JavaScript form having HTML input text tags, one for each field of Customers table.
We have also 2 navigation buttons: NextRecord and PrevRecord having at OnClick() event : clientGetRecord(NextOrPrev)
A javascript ajax clientGetRecord function, something like this:
function clientGetRecord(NextOrPrev) {
var oXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
var sURL = "ServerGetRecord.aspx?ID=" + NextOrPrev;
oXMLHTTP.open( "POST", sURL, FALSE );
oXMLHTTP.send();
var sResult=oXMLHTTP.responseText;
var aRecord = sResult.split(";");
document.getElementById('CustomerID').value = aRecord[0];
document.getElementById('CompanyName').value = aRecord[1];
document.getElementById('ContactName').value = aRecord[2];
document.getElementById('Adress').value = aRecord[3];
//... and so on ...
};
We must have something like a ServerGetRecord controler function which returns to the clientGetRecord function, a simple string containing the current record fields values separated by comma and using classic ADO database handling.
The question is : How to program and invoke the ServerGetRecord function? Can i have a VB code example of ServerGetRecord function (or ASPX, or ASHX, or something else?..) ?
Don't have any VB smaples for you, but you can create a controller (asp.net mvc) that returns a JsonResult. You get your data from the DB and build the JsonResult object to return.
Then on your client use jQuery to call the controller and get the results as json format.
This post can help you get started: Link
Hope this helps

Resources