Ajax WebGrid Paging MVC3 - ajax

I'm using WebGrid and I need to switch between pages with Ajax.
Index Code
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
#using (Ajax.BeginForm("GetGrid", new AjaxOptions() { UpdateTargetId = "Res" }))
{
<input type="text" />
<input type="submit" value="start" />
<div id="Res">
</div>
}
Result partial view
#model IEnumerable<MvcApplication1.Controllers.Model>
<div id="grid2">
#{
var grid = new WebGrid(source:Model,rowsPerPage:6,ajaxUpdateContainerId: "grid2");
#grid.GetHtml(htmlAttributes: new { id = "grid2" },
columns: grid.Columns(
grid.Column("Someting")
));
}
</div>
Controller Code
public class ABCController : Controller
{
//
// GET: /ABC/
public ActionResult Index()
{
return View();
}
public static List<Model> mo = new List<Model>();
[HttpPost]
public ActionResult GetGrid()
{
for (int i = 0; i < 1000; i++)
{
mo.Add(new Model() { Someting = i.ToString() });
}
return PartialView("Result", mo);
}
}
public class Model
{
public string Someting { get; set; }
}
This work for first page but nothing happens for other pages.

After some hours i could not find some thing that help me.i noticed to html code of my page links.
page link
2
so i finally got how it's work.i add an ActioResult to my controller like this:
[HttpGet]
public ActionResult GetGrid(int page)
{
return PartialView("Result",mo);
}
and worked.i hope this be helpfull for some one

Related

View not updating when model changed

I have a single page UI, which looks like below .
on the UI there are two checkboxes, when user toggle the states of checkbox, I use ajax to post the status to HomeController in a POST action.
after updated the model in POST action with the new checkboxes states, I redirect back to GET action to return a view.
however, the UI does not refresh with the new model.
can someone help on this ? thanks.
Views/Home/Index.cshtml
#{
Layout = "_Layout";
}
#model WebApplication5.Controllers.HomeModel;
<h1>STS</h1>
<div>
<input type="checkbox" id="UseVersionCheckBox" />Use version v1 in url
</div>
<br />
<div>
<input type="checkbox" id="ResponseTypeTokenCheckBox" /> Return access token in url
</div>
<div>your check status : #Model.IsChecked</div>
<br />
<div>your text : #Model.Text </div>
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - WebApplication5</title>
</head>
<body>
#RenderBody()
<script src="~/jquery-2.1.0.min.js"></script>
#RenderSection("Scripts", required: false)
<script type="text/javascript">
$(document).ready(function () {
function fun() {
var current = $("#UseVersionCheckBox").prop("checked");
var current2 = $("#ResponseTypeTokenCheckBox").prop("checked");
alert("values as:" + current + "," + current2);
var json = {};
json.UseVersionChecked = current;
json.ResponseTypeTokenChecked = current2;
var text = JSON.stringify(json);
$.ajax({
type: "POST",
url: "Home/Index",
data: text,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (r, s, e) {
},
success: function (r) {
},
complete: function () {
}
});
}
$("#UseVersionCheckBox").click(fun);
$("#ResponseTypeTokenCheckBox").click(fun);
});
</script>
</body>
</html>
HomeController.cs
public class HomeController : Controller
{
public HomeController()
{
}
public IActionResult Index()
{
HomeModel model;
if (TempData.ContainsKey("model"))
{
var newmodel = JsonConvert.DeserializeObject<HomeModel>(TempData["model"].ToString());
model = newmodel;
}
else
{
model = new HomeModel();
model.IsChecked = false;
model.Text = "not checked";
}
ModelState.Clear();
return View(model);
}
[HttpPost]
public IActionResult Index([FromBody] CheckStatus status)
{
HomeModel model = new HomeModel();
model.IsChecked = true;
model.Text = "UseVersionCheckBox : " + status.UseVersionChecked + " ; ResponseTypeTokenCheckbox : " + status.ResponseTypeTokenChecked;
if (TempData.ContainsKey("model"))
TempData.Remove("model");
TempData.Add("model", JsonConvert.SerializeObject(model));
ModelState.Clear();
return RedirectToAction("Index", "Home");
}
}
[Serializable]
public class HomeModel
{
public bool IsChecked { get; set; }
public string Text { get; set; }
}
public class CheckStatus
{
public bool UseVersionChecked { get; set; }
public bool ResponseTypeTokenChecked { get; set; }
}
weird thing , after checked the response of redirect to GET action, the new value is there ,but web page in browser still show old. why ?

How to get selected Drop down list value in view part of MVC?

I want to pass selected Drop down list value to Ajax Action Link which is I am using in Controller. Every time When I will change drop down list value. I want that respective value pass to the action link.
What I need to write here in Ajax Action Link ????
Drop Down List
<div class="form-group">
#Html.DropDownListFor(model => model.ComponentId, ((List<string>)ViewBag.Cdll).Select(model => new SelectListItem { Text = model, Value = model }), " -----Select Id----- ", new { onchange = "Action(this.value);", #class = "form-control" })
</div>
Ajax Action Link
<div data-toggle="collapse">
#Ajax.ActionLink("Accessory List", "_AccessoryList", new { ComponentId = ???? }, new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "divacc",
InsertionMode = InsertionMode.Replace
})
</div>
Controller
public PartialViewResult _AccessoryList(string ComponentId)
{
List<ComponentModule> li = new List<ComponentModule>();
// Code
return PartialView("_AccessoryList", li);
}
Here is a new post. I do dropdowns a little different than you, so I am showing you how I do it. When you ask what to pass, I am showing you how to pass the dropdown for 'component' being passed. I also show how to pass from ajax back to the page.
Controller/Model:
//You can put this in a model folder
public class ViewModel
{
public ViewModel()
{
ComponentList = new List<SelectListItem>();
SelectListItem sli = new SelectListItem { Text = "component1", Value = "1" };
SelectListItem sli2 = new SelectListItem { Text = "component2", Value = "2" };
ComponentList.Add(sli);
ComponentList.Add(sli2);
}
public List<SelectListItem> ComponentList { get; set; }
public int ComponentId { get; set; }
}
public class PassDDLView
{
public string ddlValue { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult PostDDL(PassDDLView passDDLView)
{
//put a breakpoint here to see the ddl value in passDDLView
ViewModel vm = new ViewModel();
return Json(new
{
Component = "AComponent"
}
, #"application/json");
}
public ActionResult IndexValid8()
{
ViewModel vm = new ViewModel();
return View(vm);
}
View:
#model Testy20161006.Controllers.ViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid8</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnClick").click(function () {
var PassDDLView = { ddlValue: $("#passThis").val() };
$.ajax({
url: '#Url.Action("PostDDL")',
type: 'POST',
data: PassDDLView,
success: function (result) {
alert(result.Component);
},
error: function (result) {
alert('Error');
}
});
})
})
</script>
</head>
<body>
<div class="form-group">
#Html.DropDownListFor(m => m.ComponentId,
new SelectList(Model.ComponentList, "Value", "Text"), new { id = "passThis" })
<input type="button" id="btnClick" value="submitToAjax" />
</div>
</body>
</html>

AJAX in MVC does not call junction

index.cshtml
<script type="text/javascript">
function OnSuccessComment(data) {
alert(data.resultMessage);
}
</script>
#using (Ajax.BeginForm(new AjaxOptions
{
Url = Url.Action("AddCommentAjax"),
OnSuccess = "OnSuccessComment",
HttpMethod = "POST"
}))
{
#Html.TextArea("comment")
<input type="submit" value="Добавить комментарий" />
}
HomeController.cs
namespace WebApplication12.Controllers
{
public class HomeController : Controller
{
private static List<string> _comments = new List<string>();
public ActionResult Index()
{
return View(_comments);
}
[HttpPost]
public ActionResult AddComment(string comment)
{
//необходимые действия
return View();
}
[HttpPost]
public ActionResult AddCommentAjax(string comment)
{
//необходимые действия
return Json(new { resultMessage = "Ваш комментарий добавлен успешно!" });
}
}
}
The problem is that function AddCommentAjax does not get called on button click. How to fix that? What is the problem?
#using (Ajax.BeginForm("AddCommentAjax", "Home", new AjaxOptions { OnSuccess = "OnSuccessComment",
HttpMethod = "POST"
}))
Try something like this
Don't forget to include javascript file:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

How to send Model value as parameter while submitting #Ajax.Beginform()

I am using #Ajax.Beginform in my View which is tightly bound to the ViewModel.
I've #Html.ListBoxFor inside my form. I add and delete items from the listbox using jQuery. Now what I am want to achieve is that onpress of the submit button, it should send full data present in the listbox regardless of which are selected. Currently it sends the list to controller if I select all the item in the listbox and press submit button. But I don't want to do that. Any idea as to how to achieve this?
Can it be sent as a form parameter.
#using (Ajax.BeginForm("SaveTextComponent", "LoanFilterEditor", new{ param1 = Model.listBoxItem}, new AjaxOptions { HttpMethod = "POST", OnSuccess = "SUCCESS" }))
I try to accept the parameter in the controller like this
public ActionResult SaveTextComponent(TextComponentViewModel model, List<SelectListItem> list)
{
}
But list is null.. Please help.
Maybe you can use this javascript to select all items at your listbox and then, send it to controller:
function listbox_selectall(listID, isSelect) {
var listbox = document.getElementById(listID);
for(var count=0; count < listbox.options.length; count++) {
listbox.options[count].selected = isSelect;
}
}
And after that, you can call the function on your form in this way:
<script>
function submit() {
listbox_selectall('righthand_side_listbox_id', true);
return true;
}
</script>
<form onsubmit="return submit()">
...
</form>
Credits to Viral Patel blog
You can follow my example:
Model:
pulic class TextComponentViewModel {
public int[] SelectedListItem { get; set; }
public List<Item> ListItem { get; set; }
}
public class Item {
public int Id { get; set; }
public String Name { get; set; }
}
View:
#model TextComponentViewModel
#using (Ajax.BeginForm("SaveTextComponent", "LoanFilterEditor", null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "SUCCESS" }, new {name = "mainForm", id = "mainForm"}))
{
#Html.ListBoxFor(model => model.SelectedListItem , new MultiSelectList(Model.ListItem, "ID", "Name"))
for(var i = 0; i < Model.ListItem.Count();i++ )
{
#Html.HiddenFor(m => m.ListItem[i].Id)
#Html.HiddenFor(m => m.ListItem[i].Name)
}
<input type = "submit" id="submitButton" />
}
Controller:
public ActionResult SaveTextComponent(TextComponentViewModel model)
{
}
Script:
$("#submitButton").click(function(){
$("#mainForm").submit();
});

ASP MVC 3 create Partial View or Custom Helper with params

I am very new to asp.mvc 3. I am using kendoui and knockout for binding. My application looks like this sample:
ViewModel
public class MyViewModel
{
public MyViewModel()
{
Initialize();
}
public IEnumerable<string> MyOptions1 { get; set; }
public string MyChoice1 { get; set; }
public IEnumerable<string> MyOptions2 { get; set; }
public string MyChoice2 { get; set; }
private void Initialize()
{
MyOptions1 = new List<string>()
{
"OptionA",
"OptionB"
};
MyOptions2 = new List<string>()
{
"OptionC",
"OptionD"
};
}
}
Index method of Home controller
public ActionResult Index()
{
return View();
}
Index View:
<div id="optionsArea">
<table>
<tr>
<td><label>Option1:</label></td>
<td><input id="options1" data-bind="kendoDropDownList: { data: MyOptions1, value: MyChoice1 }" /></td>
</tr>
<tr>
<td><label>Option2:</label></td>
<td><input id="options2" data-bind="kendoDropDownList: { data: MyOptions2, value: MyChoice2 }" /></td>
</tr>
</table>
</div>
When Index view is loaded I am calling OptionsData method of controller which returns the populated MyViewModel as Json.
public ActionResult OptionsData()
{
var myModel = new MyViewModel();
var jsonNetResult = new JsonNetResult
{
Formatting = Formatting.Indented,
Data = myModel
};
return jsonNetResult;
}
In javascript From MyViewModel I create populated javascript viewmodel viewModel with knockout observable properties and bind it to the div in the Index View.
$(function () {
my = {
}
$.getJSON("/Home/OptionsData", function (data) {
// create observable properties from MyViewModel
my.viewModel = ko.mapping.fromJS(data);
ko.applyBindings(my.viewModel, document.getElementById("optionsArea"));
});
});
In my application I have many elements containing label and dropdown so I want to extract that part in something like a component and reuse it calling it with some parameters to replace the bindings. I read some articles and maybe the solution is to use partial views or custom HTML helpers so I can do something like this:
_OptionPartialView
<tr>
<td><label>Option2:</label></td>
<td><input data-bind="kendoDropDownList: { data: (parameter1), value: (parameter2) }" /></td>
</tr>
where somehow I want to replace parameter1 and parameter 2 when I call the partial in the Index View:
#Html.Partial("_OptionPartialView.cshtml", parameter1, parameter2);
or with helper method:
#Html.MyCustomHelper(..., parameter1, parameter2);
Then I will strongly bind my Index method to the Index view:
public ActionResult Index()
{
var myModel = new MyViewModel();
return View(myModel);
}
And my view will look something like this:
#model MVC3Question.Models.MyViewModel
<div id="optionsArea">
<table>
#Html.Partial("_OptionPartialView.cshtml", Model.MyOptions1, Model.MyChoice1);
#Html.Partial("_OptionPartialView.cshtml", Model.MyOptions2, Model.MyChoice2);
</table>
</div>
My question is which is better in this situation Partial View or Custom Helper method and more important how do I implement them with the parameters having in mind the posted sample code. Any other approches or ideas are welcome. Thanks!
In my opinion both methods are good.
You can create a custom helper that takes two parameters like this:
public static MvcHtmlString MyHtmlHelper(this HtmlHelper htmlHelper, string label, IEnumerable<string> option, string choise)
{
var html = new MvcHtmlString(String.Empty);
html = MvcHtmlString.Create("<tr><td><label>" + label + ":</label></td><td><input data-bind=\"kendoDropDownList: { data: (" + option + "), value: (" + choise + ") }\" /></td></tr>");
return html;
}
I would prefer this method because it will work without any change in your current code.
If you want to use a partial view you will need to change your current model.
public class MyViewModel
{
public MyViewModel()
{
MyOptions = new List<string();
}
public IEnumerable<string> MyOptions { get; set; }
public string MyChoice { get; set; }
}
Then you can populate the model in your controller like this:
public ActionResult Index()
{
var viewModels = new List<MyViewModel>();
var myOptions1 = new List<string>()
{
"OptionA",
"OptionB"
};
var myOptions2 = new List<string>()
{
"OptionC",
"OptionD"
};
viewModels.Add(new MyViewModel{MyOptions = myOptions1});
viewModels.Add(new MyViewModel{MyOptions = myOptions2});
return View(viewModels);
}
After that you need to change your view like this:
#model IList<MVC3Question.Models.MyViewModel>
<div id="optionsArea">
<table>
#foreach(var viewModel in Model)
{
#Html.Partial("_OptionPartialView.cshtml", viewModel);
}
</table>
</div>
And finally create a partial view:
#model Mvc3Question.Models.MyViewModel
<tr>
<td><label>Option2:</label></td>
<td><input data-bind="kendoDropDownList: { data: (#Model.MyOptions), value: (#Model.MyChoice) }" /></td>
</tr>
I hope this helps.

Resources