ajax request to return partial view - asp.net-mvc

I'm trying to make request returns on ajax updated partial view. Apparently request is not returned from the ajax-function.
Here ajax-code:
<script type="text/javascript">
function doAjaxPost(myid) {
// get the form values
var ApplSort = $('#DropDownListSort').val();
var radio_check_val=0;
for (i = 0; i < document.getElementsByName('radio').length; i++) {
if (document.getElementsByName('radio')[i].checked) {
radio_check_val = document.getElementsByName('radio')[i].value;
}
}
// alert("myid=" + myid +";"+ "ApplSort=" + ApplSort + ";" + "radio_check_val=" + radio_check_val);
$.ajax(
{
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: { ApplSort: ApplSort, radio_check_val: radio_check_val, myid: myid },
UpdateTargetId: "tabledata",
dataType: 'html',
url: 'Partner/PartnerApplications',
success: function (data) {
var result = data;
$('tabledata').html(result);
},
error: function (error) {
alert('Ошибка AJAX-запроса. Обновите страницу!');
}
});
}
</script>
Fail is called and the page is completely updated.
Here's updated content in the view:
<div id="target">
#Html.Partial("~/Views/Partner/PartnerApplicationsPartial.cshtml")
</div>
controller's code:
[HttpPost]
public ActionResult PartnerApplications(int[] ApplSort, int[] radio_check_val, int[] myid)
{
MordaPartner MrdPrt = new MordaPartner(Server, Request);
if (Request.IsAjaxRequest())
{
var obj = MrdPrt.morda_obj.CookieAuthenticationPartner(Server, Request, Response, MrdPrt.PartnerLogin, MrdPrt.PartnerPassword);
if (obj != null)
{
//alert("ApplSort=" + ApplSort + ";" + "ApplSelectOffer=" + ApplSelectOffer + ";" + "ApplSelectAuction=" + ApplSelectAuction + ";" + "ApplSelectNoOffer=" + ApplSelectNoOffer);
var objs = from s in MrdPrt.morda_obj.entities.applications where s.application_user_city == obj.partner_city & s.application_blocked != 1 orderby s.application_id ascending select s;
return Json(new { data = this.RenderPartialViewToString("PartnerApplicationsPartial", objs) });
}
else
{
return RedirectToAction("Registration");
}
}
else { return RedirectToAction("PartnerApplications"); }
}
RenderPartialViewToString it was taken from here: http://www.c-sharpcorner.com/blogs/7150/implementing-renderpartialviewtostring-in-asp-net-mvc-3.aspx
script is loaded:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
What am I doing wrong?

I think your easiest solution since you are just wanting to do a partial...
#using( Ajax.BeginForm( "PartnerApplications",
null,
new AjaxOptions() {
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "target",
LoadingElementId = "AjaxSearch" },
new { id = "UserSearchForm" } ) ) {
<input type="text" id="id" name="id" placeholder="Enter Search" />
}
This is an ability that is built into MVC that makes it VERY easy to update an element with the results of a partial.
All this is saying is that you want a new Ajax Form that calls the PartnerApplications Action. You want the action called with an HttpMethod that is a POST request and you want the results to replace (InsertionMode.Replace) the existing elements in the target (whatever that may be) and while the request is taking place you want the element AjaxSearch visible (this is optional, but something I use to show that it's working).
This will generate the required JavaScript for you and until you get into something beyond simply returning a partial works EXCELLENT!
EDIT: Also you will need to update your Action...
return Json(new { data = this.RenderPartialViewToString("PartnerApplicationsPartial", objs) });
needs changed to....
return PartialView("PartnerApplicationsPartial", objs);
EDIT BASED ON COMMENTS:
Without knowing the data better that is being sent to the server I can't tell you what to write in order to replace that method. I would however look at the properties of new AjaxOptions(){} because it has some additional properties that allow you to specify the name of a JavaScript function to call on four states (before/after/success/fail) of the Ajax request. So if you are needing to calculate something you can do this by specifying a JavaScript function that will be processed before the Ajax request is submitted.
Also you are doing a lot more work then needed to get the selected radio button value (especially since you are using jQuery).
You can replace...
var radio_check_val=0;
for (i = 0; i < document.getElementsByName('radio').length; i++) {
if (document.getElementsByName('radio')[i].checked) {
radio_check_val = document.getElementsByName('radio')[i].value;
}
}
with something similar to....
var radio_check_val = $('radio').filter(':checked').val();
//this will only work if there is only one set of radio buttons on the page.
//Otherwise you will need to add a name to the selector.

You should not RedirectToAction. Instead of redirect return PartialView('Registration');.
Related questions:
MVC Return Partial View as JSON.
Load PartialView for AJAX and View for non-AJAX request

Related

Print out to a div in the view from the controller

I have a div block in my view like this:
<div id="divStatus" style="margin-top:10px;width: 200px; height: 100px; overflow-y: scroll;">
</div>
then from the view, user clicks on a button that calls the controller. In the controller some tasks are executed so from the controller I want to update a div block within the view. In this div I print out phrasses.
How to do this?
example:
public ActionResult()
{
// Do something
Update_DIV_in_View("some thing has been done"); <--- DIV in the view must be updated by appending this message
// Do another thing
Update_DIV_in_VIEW("another thing has been done");<--- DIV in the view must be updated by appending this message
.... and so on
// All things done
Update_DIV_in_VIEW("All things have been done");<--- DIV in the view must be updated by appending this message
return View();
}
Create a second action in your controller which only shows the updated content of the div and on your normal page when you press the button load the status with an AJAX call (for example the jQuery.load() method).
You can do it as follows:
In your view use Ajax Form as follows:
#using (Ajax.BeginForm("ActionName", "ControllerName", new AjaxOptions { OnBegin = "beforeSubmitFunction()", HttpMethod = "POST",UpdateTargetId = "divStatus", OnComplete = "InsertRow()" }))
{
.. //your Html form Controls
}
function beforeSubmitFunction()
{
//Your code for before submitting...
}
Then in your controller return your partial view as result which will get updated in your div with id divStatus
[HttpPost]
public ActionResult Index(TypeName model)
{
return PartialView("PartialViewName", model);
}
Here are 3 examples what I am using:
example 1:
button (here with telerik css styling):
<a class="t-button t-button-icontext" onclick="ajaxCreateEquipment()"><span
class="t-icon t-add"></span>Create</a>
javascript: #equipment-table-container is the id of the target div:
<script type="text/javascript">
function ajaxCreateEquipment() {
$.ajax({
type: 'GET',
url: '#Url.Action("ShowCreate", "Equipment")',
dataType: 'html',
success: function (data) {
$('#equipment-table-container').html(data);
}
});
}
</script>
EquipmentController.cs:
[HttpGet]
public ActionResult ShowCreate()
{
// some calculation code, fetch model from DB something else
ViewData.Add("FormAction", "Create"); // some ViewData
return PartialView("Create", model); // returns the View html file
}
example 2:
function call here with id argument and Json return:
#{
var supplierQuoteId = Model.ID.ToString();
<a id="#supplierQuoteId" onclick="updateDiv(this.id)"></a>
}
javascript:
function updateDiv(id) {
var strUrl = "/LicenseTerm/UpdateUsedQuantity/" + id;
$.ajax({
type: "GET",
url: strUrl,
cache: false,
dataType: "json",
success: function (data) {
$('#licenseterm-usedquantity').html(data.sum);
}
});
}
LicenseTermController.cs
[HttpGet]
public JsonResult UpdateUsedQuantity(Guid id)
{
var licenseTerm = _repository.GetAll<LicenseTerm>().Where(l => l.ID == id).First();
int sum = 0;
foreach (LicenseAllocation l in licenseTerm.LicenseAllocations.Where(o => o.Deleted == false))
sum = sum + l.LicenseQuantity;
return Json(new { sum = sum }, JsonRequestBehavior.AllowGet);
}
example 3: simple get
function ajaxFieldDefinitionCreate(id) {
var strUrl = '/FieldDefinition/Create' + '/' + id.toString() + '?isRefreshAction=true';
$.get(strUrl, function (data) {
$('#equipmenttype-fielddefinition-createeditarea').html(data);
});
}
[HttpGet]
public ActionResult Create(Guid id, [Optional, DefaultParameterValue(false)] bool isRefreshAction)
{
var equipmentType = _equipmentTypeRepository.GetById(id);
var fieldDefinitionDto = new FieldDefinitionDto
{
ID = Guid.NewGuid(),
ParentName = equipmentType.Name,
};
return PartialView("Create", fieldDefinitionDto);
}
In response to the changes of the question, especially that the questioner would like to have more returns in the same Action:
the concept of HTTP request is to transmit relatively small pieces of data from the server to the client, which invoked the e.g. HTTP GET request.
You can not keep open the HTTP GET request for more transmissions.
I searched the web and extracted that especially HTML5 will address this requirement with the HTTP stream, but this is another topic. e.g.: I got this url: http://socket.io/ .
Bypass:
But as an idea of mine,
I would make a first ajax call to determine the count of the next requests, addressed in the controller Action1.
And then invoke several new requests in the success part of the first ajax request, with the url of the Action2, e.g. Calculate etc., which appends then the several pieces of data to the div content.
here some quickly invented javascript code:
function updateDiv() {
var strUrl = "/Home/RequestCount/";
$.ajax({
type: "GET",
url: strUrl,
cache: false,
dataType: "json",
success: function (count) {
var strUrlCalc = "/Home/Calc/";
for (var i = 0; i < count; i++) {
$.ajax({
type: "GET",
url: strUrlCalc,
cache: false,
dataType: "json",
success: function (data) {
$('#test').append(data);
}
});
}
}
});
}

Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON

I've got a cascading drop-drown using mvc. Something like, if you select a country in the first-dropdown, the states of that country in the second one should be populated accordingly.
At the moment, all seems fine and I'm getting Json response (saw it using F12 tools), and it looks something like [{ "stateId":"01", "StateName": "arizona" } , { "stateId" : "02", "StateName":"California" }, etc..] ..
I'd like to know how to populate my second-dropdown with this data. My second drop-down's id is "StateID". Any help would be greatly appreciated.
Below is the code used to produce the JSON Response from the server:
[HttpPost]
public JsonResult GetStates(string CountryID)
{
using (mdb)
{
var statesResults = from q in mdb.GetStates(CountryID)
select new Models.StatesDTO
{
StateID = q.StateID,
StateName = q.StateName
};
locations.statesList = stateResults.ToList();
}
JsonResult result = new JsonResult();
result.Data = locations.statesList;
return result;
}
Below is the client-side HTML, my razor-code and my script. I want to write some code inside "success:" so that it populates the States dropdown with the JSON data.
<script type="text/javascript">
$(function () {
$("select#CountryID").change(function (evt) {
if ($("select#CountryID").val() != "-1") {
$.ajax({
url: "/Home/GetStates",
type: 'POST',
data: { CountryID: $("select#CountryID").val() },
success: function () { alert("Data retrieval successful"); },
error: function (xhr) { alert("Something seems Wrong"); }
});
}
});
});
</script>
To begin with, inside a jQuery event handler function this refers to the element that triggered the event, so you can replace the additional calls to $("select#CountryID") with $(this). Though where possible you should access element properties directly, rather than using the jQuery functions, so you could simply do this.value rather than $(this).val() or $("select#CountryID").val().
Then, inside your AJAX calls success function, you need to create a series of <option> elements. That can be done using the base jQuery() function (or $() for short). That would look something like this:
$.ajax({
success: function(states) {
// states is your JSON array
var $select = $('#StateID');
$.each(states, function(i, state) {
$('<option>', {
value: state.stateId
}).html(state.StateName).appendTo($select);
});
}
});
Here's a jsFiddle demo.
Relevant jQuery docs:
jQuery.each()
jQuery()
In my project i am doing like this it's below
iN MY Controller
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
In Model
public IQueryable<Models.State> GetList(int CountryID)
{
var statelist = db.States.Where(x => x.CountryID == CountryID).ToList().Select(item => new State
{
ID = item.ID,
StateName = item.StateName
}).AsQueryable();
return statelist;
}
In view
<script type="text/javascript">
function cascadingdropdown() {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
var countryID = $('#countryID').val();
var Url="#Url.Content("~/City/State")";
$.ajax({
url:Url,
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
}
});
}
</script>
i think this will help you......
Step 1:
At very first, we need a model class that defines properties for storing data.
public class ApplicationForm
{
public string Name { get; set; }
public string State { get; set; }
public string District { get; set; }
}
Step 2:
Now, we need an initial controller that will return an Index view by packing list of states in ViewBag.StateName.
public ActionResult Index()
{
List<SelectListItem> state = new List<SelectListItem>();
state.Add(new SelectListItem { Text = "Bihar", Value = "Bihar" });
state.Add(new SelectListItem { Text = "Jharkhand", Value = "Jharkhand" });
ViewBag.StateName = new SelectList(state, "Value", "Text");
return View();
}
In above controller we have a List containing states attached to ViewBag.StateName. We could get list of states form database using Linq query or something and pack it to ViewBag.StateName, well let’s go with in-memory data.
Step 3:
Once we have controller we can add its view and start creating a Razor form.
#Html.ValidationSummary("Please correct the errors and try again.")
#using (Html.BeginForm())
{
<fieldset>
<legend>DropDownList</legend>
#Html.Label("Name")
#Html.TextBox("Name")
#Html.ValidationMessage("Name", "*")
#Html.Label("State")
#Html.DropDownList("State", ViewBag.StateName as SelectList, "Select a State", new { id = "State" })
#Html.ValidationMessage("State", "*")
#Html.Label("District")
<select id="District" name="District"></select>
#Html.ValidationMessage("District", "*")
<p>
<input type="submit" value="Create" id="SubmitId" />
</p>
</fieldset>
}
You can see I have added proper labels and validation fields with each input controls (two DropDownList and one TextBox) and also a validation summery at the top. Notice, I have used which is HTML instead of Razor helper this is because when we make JSON call using jQuery will return HTML markup of pre-populated option tag. Now, let’s add jQuery code in the above view page.
Step 4:
Here is the jQuery code making JSON call to DDL named controller’s DistrictList method with a parameter (which is selected state name). DistrictList method will returns JSON data. With the returned JSON data we are building tag HTML markup and attaching this HTML markup to ‘District’ which is DOM control.
#Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
$(function () {
$('#State').change(function () {
$.getJSON('/DDL/DistrictList/' + $('#State').val(), function (data) {
var items = '<option>Select a District</option>';
$.each(data, function (i, district) {
items += "<option value='" + district.Value + "'>" + district.Text + "</option>";
});
$('#District').html(items);
});
});
});
</script>
Please make sure you are using jQuery library references before the tag.
Step 5:
In above jQuery code we are making a JSON call to DDL named controller’s DistrictList method with a parameter. Here is the DistrictList method code which will return JSON data.
public JsonResult DistrictList(string Id)
{
var district = from s in District.GetDistrict()
where s.StateName == Id
select s;
return Json(new SelectList(district.ToArray(), "StateName", "DistrictName"), JsonRequestBehavior.AllowGet);
}
Please note, DistrictList method will accept an ‘Id’ (it should be 'Id' always) parameter of string type sent by the jQuery JSON call. Inside the method, I am using ‘Id’ parameter in linq query to get list of matching districts and conceptually, in the list of district data there should be a state field. Also note, in the linq query I am making a method call District.GetDistrict().
Step 6:
In above District.GetDistrict() method call, District is a model which has a GetDistrict() method. And I am using GetDistrict() method in linq query, so this method should be of type IQueryable. Here is the model code.
public class District
{
public string StateName { get; set; }
public string DistrictName { get; set; }
public static IQueryable<District> GetDistrict()
{
return new List<District>
{
new District { StateName = "Bihar", DistrictName = "Motihari" },
new District { StateName = "Bihar", DistrictName = "Muzaffarpur" },
new District { StateName = "Bihar", DistrictName = "Patna" },
new District { StateName = "Jharkhand", DistrictName = "Bokaro" },
new District { StateName = "Jharkhand", DistrictName = "Ranchi" },
}.AsQueryable();
}
}
Step 7:
You can run the application here because cascading dropdownlist is ready now. I am going to do some validation works when user clicks the submit button. So, I will add another action result of POST version.
[HttpPost]
public ActionResult Index(ApplicationForm formdata)
{
if (formdata.Name == null)
{
ModelState.AddModelError("Name", "Name is required field.");
}
if (formdata.State == null)
{
ModelState.AddModelError("State", "State is required field.");
}
if (formdata.District == null)
{
ModelState.AddModelError("District", "District is required field.");
}
if (!ModelState.IsValid)
{
//Populate the list again
List<SelectListItem> state = new List<SelectListItem>();
state.Add(new SelectListItem { Text = "Bihar", Value = "Bihar" });
state.Add(new SelectListItem { Text = "Jharkhand", Value = "Jharkhand" });
ViewBag.StateName = new SelectList(state, "Value", "Text");
return View("Index");
}
//TODO: Database Insertion
return RedirectToAction("Index", "Home");
}
Try this inside the ajax call:
$.ajax({
url: "/Home/GetStates",
type: 'POST',
data: {
CountryID: $("select#CountryID").val()
},
success: function (data) {
alert("Data retrieval successful");
var items = "";
$.each(data, function (i, val) {
items += "<option value='" + val.stateId + "'>" + val.StateName + "</option>";
});
$("select#StateID").empty().html(items);
},
error: function (xhr) {
alert("Something seems Wrong");
}
});
EDIT 1
success: function (data) {
$.each(data, function (i, val) {
$('select#StateID').append(
$("<option></option>")
.attr("value", val.stateId)
.text(val.StateName));
});
},
I know this post is a year old but I found it and so might you. I use the following solution and it works very well. Strong typed without the need to write a single line of Javascript.
mvc4ajaxdropdownlist.codeplex.com
You can download it via Visual Studio as a NuGet package.
You should consider using some client-side view engine that binds a model (in your case JSON returned from API) to template (HTML code for SELECT). Angular and React might be to complex for this use case, but JQuery view engine enables you to easily load JSON model into template using MVC-like approach:
<script type="text/javascript">
$(function () {
$("select#CountryID").change(function (evt) {
if ($("select#CountryID").val() != "-1") {
$.ajax({
url: "/Home/GetStates",
type: 'POST',
data: { CountryID: $("select#CountryID").val() },
success: function (response) {
$("#stateID").empty();
$("#stateID").view(response);
},
error: function (xhr) { alert("Something seems Wrong"); }
});
}
});
});
</script>
It is much cleaner that generating raw HTML in JavaScript. See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown
Try this:
public JsonResult getdist(int stateid)
{
var res = objdal.getddl(7, stateid).Select(m => new SelectListItem { Text = m.Name, Value = m.Id.ToString() });
return Json(res,JsonRequestBehavior.AllowGet);
}
<script type="text/javascript">
$(document).ready(function () {
$("#ddlStateId").change(function () {
var url = '#Url.Content("~/")' + "Home/Cities_SelectedState";
var ddlsource = "#ddlStateId";
var ddltarget = "#ddlCityId";
$.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$.each(data, function (index, optionData) {
$(ddltarget).append("<option value='" + optionData.Text + "'>" + optionData.Value + "</option>");
});
});
});
});
</script>

How to submit local jqgrid data and form input elements

Page contains single form with input elements and jqgrid data.
jqGrid data is retrieved in json using loadonce: true option.
Data is edited locally.
How to submit all this data if submit button is pressed?
Has jqGrid any method which can help to submit all data from all rows. jqGrid - How to edit and save multiple rows at once? mentions that jQuery ajax form plugin should be used but I havent found any sample.
jqGrid probably holds retrieved json table in element. In this case form plugin is not capable read this data.
How to get and submit all data retrieved using loadonce: true and edited?
Update1
Based on Oleg answer I tried:
function SaveDocument() {
var gridData = $("#grid").jqGrid('getGridParam','data');
var postData = JSON.stringify(gridData);
$('#_detail').val( postData );
var res = $("#Form").serializeArray();
$.ajax({ type: "POST",
url: 'Edit'
data : res
});
}
}
aspx page:
<form id="Form" class='form-fields'>
.... other form fields
<input name='_detail' id='_detail' type='hidden' />
</form>
<div id="grid1container" style="width: 100%">
<table id="grid">
</table>
</div>
In ASP.NET MVC2 Controller Edit method I tried to parse result using
public JsonResult Edit(string _detail) {
var order = new Order();
UpdateModel(order, new HtmlDecodeValueProviderFromLocalizedData(ControllerContext));
var serializer = new JavaScriptSerializer();
var details = serializer.Deserialize<List<OrderDetails>>>(_detail);
}
Exception occurs in Deserialize() call. Decimal and date properties are passed in localized format but it looks like Deserialize() does not parse
localized strings and there is no way to force it to use converter like HtmlDecodeValueProviderFromLocalizedData passed to UpdateModel.
How to fix ?
Is is reasonable/how to convert _detail parameter into NameValue collection and then use UpdateModel to update details, use some other deserialize or other idea ?
Update 2.
Decimal and Date CurrentUICulture values are present in form and in jqGrid data. Sample provided handles them in form OK but fails for jqGrid data.
This controller should handle different entity types, form fields and jqgrid columns can defined at runtime. So using hard-coded names is not possible.
Based on Oleg reply I tried to override decimal conversion by creating converter
public class LocalizedTypeConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get
{
return new ReadOnlyCollection<Type>(new Type[] { typeof(decimal) });
}
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type,
JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (type == typeof(decimal))
return decimal.Parse(dictionary["resources"].ToString(), CultureInfo.CurrentCulture);
return null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new InvalidOperationException("We only Deserialize");
}
}
But conversion still causes exception
0,0000 is not valid value for decimal. It looks like decimal converter cannot overridden. How to fix ?
First of all you can get all local data from the jqGrid with respect of
var localGridData = $("#list").jqGrid('getGridParam','data');
If you will need to send only subset of rows of the grid, like the selected rows only, you can need to get _index:
var idsToDataIndex = $("#list").jqGrid('getGridParam','_index');
To send the data to the server you can use the following function for example
var sendData = function(data) {
var dataToSend = JSON.stringify(data);
alert("The following data are sending to the server:\n" + dataToSend);
$.ajax({
type: "POST",
url: "yourServerUrl",
dataType:"json",
data: dataToSend,
contentType: "application/json; charset=utf-8",
success: function(response, textStatus, jqXHR) {
// display an success message if needed
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
// display an error message in any way
alert("error");
}
});
};
In the demo you will find a little more sophisticated example having two buttons: "Send all grid contain", "Send selected rows". The corresponding code is below
$("#sendAll").click(function(){
var localGridData = grid.jqGrid('getGridParam','data');
sendData(localGridData);
});
$("#sendSelected").click(function(){
var localGridData = grid.jqGrid('getGridParam','data'),
idsToDataIndex = grid.jqGrid('getGridParam','_index'),
selRows = grid.jqGrid('getGridParam','selarrrow'),
dataToSend = [], i, l=selRows.length;
for (i=0; i<l; i++) {
dataToSend.push(localGridData[idsToDataIndex[selRows[i]]]);
}
sendData(dataToSend);
});
where
var grid = $("#list"),
decodeErrorMessage = function(jqXHR, textStatus, errorThrown) {
var html, errorInfo, i, errorText = textStatus + '\n<br />' + errorThrown;
if (jqXHR.responseText.charAt(0) === '[') {
try {
errorInfo = $.parseJSON(jqXHR.responseText);
errorText = "";
for (i=0; i<errorInfo.length; i++) {
if (errorText.length !== 0) {
errorText += "<hr/>";
}
errorText += errorInfo[i].Source + ": " + errorInfo[i].Message;
}
}
catch (e) { }
} else {
html = /<body.*?>([\s\S]*)<\/body>/i.exec(jqXHR.responseText);
if (html !== null && html.length > 1) {
errorText = html[1];
}
}
return errorText;
},
sendData = function(data) {
var dataToSend = JSON.stringify(data);
alert("The following data are sending to the server:\n"+dataToSend);
$.ajax({
type: "POST",
url: "yourServerUrl",
dataType:"json",
data: dataToSend,
contentType: "application/json; charset=utf-8",
success: function(response, textStatus, jqXHR) {
// remove error div if exist
$('#' + grid[0].id + '_err').remove();
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
// remove error div if exist
$('#' + grid[0].id + '_err').remove();
// insert div with the error description before the grid
grid.closest('div.ui-jqgrid').before(
'<div id="' + grid[0].id + '_err" style="max-width:' + grid[0].style.width +
';"><div class="ui-state-error ui-corner-all" style="padding:0.7em;float:left;"><span class="ui-icon ui-icon-alert" ' +
'style="float:left; margin-right: .3em;"></span><span style="clear:left">' +
decodeErrorMessage(jqXHR, textStatus, errorThrown) + '</span></div><div style="clear:left"/></div>');
}
});
};
I think, that more difficult and more complex problem you will become on the server. In case of concurrency errors, but I wrote you about the problems before. Exactly because of the problems I personally would never implement saving of multiple rows on the server.
UPDATED: To get data from the form you can use jQuery.serialize. You should use name attribute for all fields in the form which you want to serialize. All data which you need to send are
var allData = {
localGridData: grid.jqGrid('getGridParam','data'),
formData: $("#formid").serialize()
};
You can send the data exactly like I described before: sendData(allData).

Get the Current ViewContext in ASP.Net MVC

I have a ASP.Net MVC JsonResult function in which I want to return the contents of a PartialView (The content has to be loaded using Ajax, and for some reason I can't return a PartialViewResult).
To render the PartialView I need the ViewContext object.
How do you get the current ViewContext object within an Action method? I don't even see HttpContext.Current in my action method.
I am using ASP.net MVC 1.
a ViewContext is not available within the action method because it is constructed later before rendering the view. I would suggest you using MVCContrib's BlockRenderer to render the contents of a partial view into a string.
I may have missed a point somewhere but my Actions that returned partial views do so by returning a View object that refers to an ascx page. This will return partial HTML without the full page constructs (html, head, body, etc.). Not sure why you'd want to do anything beyond that, is there a specific reason you need to return PartialViewResult? Here's an example from my working code.
First the Action in my controller:
public ViewResult GetPrincipleList(string id)
{
if (id.Length > 1)
id = id.Substring(0, 1);
var Principles = competitorRepository.Principles.Where(p => p.NaturalKey.StartsWith(id)).Select(p=>p);
return View(Principles);
}
And then the partial view (ascx):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MyProject.Data.Principle>>" %>
<% foreach (var item in Model) { %>
<div class="principleTitle" title="<%= Html.Encode(item.NaturalKey) %>"><%= Html.Encode(item.Title) %></div>
<%} %>
Lastly, the Jquery that sets up the call:
$(function() {
$(".letterSelector").click(function() {
$("#principleList").load("/GetPrincipleList/" + $(this).attr("title"), null, setListClicks);
});
});
So, a full AJAX process, hope that helps.
---- UPDATE following comment ----
Returning Json data is just as easy:
Firstly, initiating the AJAX call when a select box changes:
$("#users").change(function() {
var url = "/Series/GetUserInfo/" + $("#users option:selected").attr("value");
$.post(url, null, function(data) { UpdateDisplay(data); }, 'json');
});
The javascript that processes the returned json data:
function UpdateDisplay(data) {
if (data != null) {
$("div.Message").fadeOut("slow", function() { $("div.Message").remove(); });
$("#Firstname").val(data.Firstname);
$("#Lastname").val(data.Lastname);
$("#List").val(data.List);
$("#Biography").val(data.Biography);
if (data.ImageID == null) {
$("#Photo").attr({ src: "/Content/Images/nophoto.png" });
$("#ImageID").val("");
}
else {
if (data.Image.OnDisk) {
$("#Photo").attr({ src: data.Image.ImagePath });
}
else {
$("#Photo").attr({ src: "/Series/GetImage?ImageID=" + data.ImageID });
}
$("#ImageID").val(data.ImageID);
}
$("form[action*='UpdateUser']").show();
} else {
$("form[action*='UpdateUser']").hide();
}
};
And finally the Action itself that returns the json data:
public JsonResult GetUserInfo(Guid id)
{
MyUser myuser = (from u in seriesRepository.Users
where u.LoginID == id
select u).FirstOrDefault();
if (myuser == null)
{
myuser = new MyUser();
myuser.UserID = 0;
myuser.Firstname = Membership.GetUser(id).UserName;
myuser.Lastname = "";
myuser.List = "";
myuser.Biography = "No yet completed";
myuser.LoginID = id;
}
return Json(myuser);
}
Does that help? If not then can you post some of the code you are working on as I'm missing something.

How to get html returned from ActionResult in Controller

I am trying to implement a feature similar to the Related Questions on StackOverflow, I am doing this in MVC.
$().ready(function() {
var s = $("#Summary").val();
$("#Summary").blur(function() { QuestionSuggestions(s); });
});
function GetPastIssues(title) {
$(document).ready(function() {
$.ajax({ type: "POST",
url: "/Issue/GetSimilarIssues",
contentType: "application/json; charset=utf-8",
dataType: "xml",
dataType: "json",
data: "{'title':'" + title + "'}",
processData: false,
error: function(XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); },
success: function(xml) { ajaxFinish(xml); }
});
});
function ajaxFinish(xml) {
if (xml.d != "NO DATA") {
$('#question-suggestions').html(xml.d); //alert(xml.d); // This ALERT IS returning undefined
$('#question-suggestions').show();
}
}
The data being returned from my controller is 'undefined', as shown by the commented line in ajaxFinish.
What am I doing wrong?
//[AcceptVerbs(HttpVerbs.Get)]
[JsonParamFilter(Param = "title", TargetType = typeof(string))]
public ActionResult GetSimilarIssues(string title)
{
var issues = _db.GetSimilarIssues(title).ToList();
if (title == null || issues.Count() == 0)
return Json("NO DATA");
string retVal = null;
foreach (Issue issue in _db.GetSimilarIssues(title))
{
retVal += "<div class='answer-summary' style='width: 610px;'>";
retVal += "<a href='Issue.aspx?projid=" + issue.ProjectId.ToString() + "&issuetypeid=" + issue.IssueTypeId.ToString() +
"&issueid=" + issue.IssueId.ToString() + "'>";
retVal += issue.Summary;
retVal += "</a>";
retVal += "</div>";
}
return Json(retVal);
}
EDIT:
I think what will help me learn and implement a solution to my senario is if I can get some insight into how StackOverflow implements this javascript method:
function QuestionSuggestions() {
var s = $("#title").val();
if (s.length > 2) {
document.title = s + " - Stack Overflow";
$("#question-suggestions").load("/search/titles?like=" + escape(s));
}
Looks like a 'Search' folder in the Views folder and a PartialView called 'Title'. A SearchController.cs with the following method:
public ActionResult titles(string like)
{
// HOW TO IMPLEMENT THIS
return PartialView("Titles");
}
What goes in the Titles.ascx to display the html?
The purpose of JSON() is to return a JSON object -- not HTML. JSON object would be something like {html_value: "<li>blah" }. I'm not sure what your ajax request is expecting. If it is expecting JSON (you have dataType set twice), then you can do something like with an anonymous object:
return Json(new {html_value = retVal});
However, if you want to return HTML from your controller -- don't. That's exactly what a view is for. Create a view without any master page and do the loop and return the HTML that way. Ajax apps can take this HTML and drop it wherever necessary.
In fact, while you technically could do the above anonymous object (where you return the html inside of a json object), this isn't what it's for. If you want to use JSON you should be returning values, and letting the javascript on the client format it:
I'm not sure how "heavy" your issues object is, but assume that it only has the three fields you're using. In that case, do:
return Json(issues);
EDIT:
Well, I think "Best Practice" would be to return just the values via JSON and format within the javascript. I'm not familiar enough with JSON(), but I know it works (I'm using it for something simple). Try creating a simple issues object with just those three values and
return Json(issuesTxfr);
You don't need to use partialviews as you're calling from a controller. Just think of it as a very simple view. Here's an example of mine (please don't notice that I'm not following my own JSON advice -- this is from a while back and I now cringe looking at it for a few reasons):
public ActionResult Controls_Search_Ajax(string q, string el)
{
...
ViewData["controls"] = controls;
ViewData["el"] = el;
return View();
}
and
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Controls_Search_Ajax.aspx.cs" Inherits="IRSoxCompliance.Views.Edit.Controls_Search_Ajax" %>
<% var controls = ViewData.Get<IEnumerable<IRSoxCompliance.Models.Control>>("controls");
var el = ViewData.Get<String>("el");
if (controls != null)
{
foreach (var c in controls)
{
%><%= c.Control_ID %>***<%= c.Full_Control_Name %>***<li id="<%= el %>:li:<%= c.Control_ID %>"><span class="item"><%= Html.BreadCrumb(c, false) %></span><span class="actions">Remove</span><br></li>
<% }
}
%>
Note the fact that there is no master page specified.
You could always return HTML as a string. I'm not saying that this is necessarily the way to go, and I do agree with James Shannon about not using JSON to return HTML.
Phil Haack wrote an excellent article about this on his blog back in May.

Resources