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);
}
});
}
}
});
}
Related
I have a function in jquery which creates a list of values being selected from a checkbox. Now I want to have this list in my controller action. I have converted this list to JSON but I am not able to pass it to the controller. I also tried creating a custom model corresponding to the json data.
Jquery Code
$("button").click(function () {
//alert("clicked");
var obj = {};
//var tempRadio = [];
for (var i = 1; i <= globalVar; i++) {
if ($("#" + i).prop("checked") == true) {
obj[i] = $('input[class=' + i + ']:checked').val();
}
}
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("SkillAdd","User")',
data: JSON.stringify(obj),
//data: hello,
error:function ()
{
alert("Error");
},
success: function () {
alert(JSON.stringify(obj));
}
});
});
Controller Code
public ActionResult SkillAdd(List<string> Id, List<string> Name)
{
return View();
}
Controller Code with Custom Model
public ActionResult SkillAdd(List<MyModel> object)
{
return View();
}
You have an object in javascript but you need to create an array so that it can be mapped to List at post. So change your js code to be :
var obj = []; // it's array now
and then you will add items in it like in your loop:
obj.push( $('input[class=' + i + ']:checked').val());
and in your ajax call name the parameter what you have in your controller action:
data:{ Id : obj }
and now you can have a parameter in action method List<string> which would hold the data posted by ajax call.
public ActionResult SkillAdd(List<string> Id)
{
return View();
}
Hope it helps.
Actually i tried to update the partial view content whenever i do search. So i use ajax call to achieve this. So, the values from the controller to partial view model is correct(new data), but its not binding to the view (shows existing data).
Main View
<div class="tab-pane active" id="partialviewpage">
#{
Html.RenderPartial("_Details", Model);
}
</div>
Partial View (_Details)
foreach (var item in Model.AllAds)
{
//div contents
}
Ajax Call
var text = 'test';
$.ajax({
url: '#Url.Action("Subcategory", "Category")',
type: 'GET',
dataType: 'JSON',
data: { item: text },
success: function (partialView) {
$('#partialviewpage').html(partialView);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Category Controller
public ActionResult Subcategory(string item)
{
//Logic calling Api content goes here
var SearchresponseData = responseMessage.Content.ReadAsStringAsync().Result;
JavaScriptSerializer JssSearch = new JavaScriptSerializer();
List<Result> Jsonresult = (List<Result>)JssSearch.Deserialize(SearchresponseData, typeof(List<Result>));
var Model= new ModelName();
{
Model.AllAds = new List<Result>();
Model.AllAds = Jsonresult;
}
return PartialView("_Details", Model);
}
So, What's wrong with my code and how can i modify the code to get the new model values. Any help appreciated. Thanks in advance.
I observed that you have used wrong variable to replace the html in success,
I have replace PartialView to partialView
var text = 'test';
$.ajax({
url: '#Url.Action("Subcategory", "Category")',
type: 'GET',
dataType: 'JSON',
data: { item: text },
success: function (partialView) {
$('#partialviewpage').html(partialView);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I have a method which return an action to a different controller. I am using return RedirectToAction and passing a parameter with it. The parameter successfully passed to the other controller. But it does not return any view. The page should load and return a new view. Here is my code:
Controller 1:
public ActionResult Work(int id, int staffId)
{
return RedirectToAction("CreateStaffWork", "Staff", new { id = staffId});
}
Controller 2 (Staff):
public ActionResult CreateStaffWork(int id)
{
Staff staffInfo= db.Staff.Find(id);
StaffInputModel newStaffWork = new StaffInputModel { StaffId = staffInfo.Id };
return View(newStaffWork);
}
It should return CreateStaffWork view, but the page does not reload. There is no error while running the code. What should I do for the view to return?
I submit the form using ajax request:
<script type="text/javascript">
$(document).ready(function () {
$("#LoadStaffListTable tbody").on('click', '.select', function (e) {
e.preventDefault();
$.ajax({
url: '/StaffWork/Work',
type: 'POST',
data: { id: $(this).data('id'), staffId: $(this).data('staffId') },
dataType: 'json',
}); // end ajax
});
});
As mentioned in the comments, the purpose of ajax is to stay in the same page. If you're redirecting to a new page, you simply redirect to the Work action methods with proper parameters.
Change your click event handler to:
$("#LoadStaffListTable tbody").on('click', '.select', function(e) {
location.href = '#Url.Action("Work", "StaffWork")?id=' + $(this).data('id') + '&staffId=' + $(this).data('staffId');
});
I've been searching around with no luck on how to make a jquery call to load a partial view in a div tag on my Index view. Some how I am not getting the partial view to update when I click on a link on my tree. The partial view loads when I first run it b/c I call <div id="divid">
#Html.Partial("_InnerView")</div>. After that nothing happens when I click on the link. Or maybe I am not getting the full picture here. Some mentioned to use $('#divid').load = data; or $('#divid').innerHTML= data; but nothing works for me. This is what I have.
Controller:
public ActionResult Test(string parentEls)
{
if (Request.IsAjaxRequest())
{
Employee employee = new Employee();
employee.Name = parentEls + "1";
return PartialView("_InnerView", employee);
}
return View("_InnerView");
}
Index view:
<div id="divid">
#Html.Partial("_InnerView")</div>
$('#tree a').click(function () {
var parentEls = $(this).parents('ul').map(function () {
return $(this).find('a').first().text();
}).get().join(", ");
$.ajax({
type: 'POST',
url: '#Url.Content("~/Home/Test")',
data: {
parentEls: parentEls
},
success: function(data) {
$('#divid').innerHTML = data;
}
});
});
_InnerView.cshtml:
#model TreeDemo.Models.Employee
EmpName:#Model.Name
UPDATE: I got this to work with this
$.ajax({ url: '/Home/Test/', contentType: 'application/html; charset=utf-8', type: 'GET', dataType: 'html', data: { parentEls: parentEls } })
You have to use
$('#divid').html(data);
instead of
$('#divid').innerHTML = data;
Load Partial View in a div MVC 4
Recently I want load Partal View in Div , after doing lots of R&D and It's work for me
$.ajax({
type: 'POST',
url: '#Url.Content("~/ControllerName/ActionName")',
data: {
title: title
},
success: function(result) {
$('#divid').innerHTML = result;
}
});
And In Partal View Action Controller Code
public PartialViewResult ShowCategoryForm(string title)
{
Model model = new Model();
model.Title = title;
return PartialView("~/Views/ControllerName/PartalView.cshtml", model);
}
I think it can be useful if you check the request/response objects of your call, so you can see what is really happening after you make the call... As per your code, I can notice that you're posting using
$.ajax({
type: 'POST',
url: '#Url.Content("~/Home/Test")',
data: {
parentEls: parentEls
},
success: function(data) {
$('#divid').innerHTML = data;
}
});
but your action is marked for 'getting'... you'd need to have something like this
[HttpPost]
public ActionResult Test(string parentEls)
so MVC can understand that the action should be called when HttpPost verb is used
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