Refresh asp.net mvc page - asp.net-mvc

I have some app on asp.net mvc.
And I am trying to create table filter. Page is very difficult, so i can't get data from JSON response. I am trying to get it via call action with params.
function refresh() {
var id = $("#list").val();
var params = { id: id };
$.get("/Home/Index", params, null, "json");
}
<select id="list" onchange="refresh()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<%foreach (var i in (IEnumerable<int>)ViewData["list"])
{ %>
<%=i %><br />
<%} %>
public ActionResult Index(int? id)
{
if (id == null)
id = 0;
ViewData["list"] = Enumerable.Range((int)id, 5).Select(i => i).ToList<int>();
return View();
}
But I don't see new data. What's wrong?
How I can refresh page?
PS I meen that i wanna go(redirect) from action A to action A(with param). I don't want reconstruct page on client side

You aren't doing anything with the result you retrieve with the get call. Also, since you're returning a view, you should set your data type to html.
$.get('/Home/Index', params, function(html) {
$('body').html(html);
},'html');
I'd note that I would probably only replace the section that gets updated. You can do this by using a partial view to hold just that section, then when you get the request via AJAX you can return just the partial view instead of the full view. The other thing that I would do is make the views strongly-typed to IEnumerable<int> and pass a model, instead of using view data.
View
<script type="text/javascript">
$(function() {
$('#list').change( function() {
var id = $("#list").val();
var params = { id: id };
$.get("/Home/Index", params, function(html) {
$('#listResults').replaceWith(html)
}, "html");
});
});
</script>
<select id="list">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<% Html.RenderPartial( "ListResults" ); %>
Partial View
<div id="listResults">
<%foreach (var i in Model)
{ %>
<%=i %><br />
<%} %>
</div>
Action
public ActionResult Index(int? id)
{
if (id == null)
id = 0;
var model = Enumerable.Range((int)id, 5).Select(i => i).ToList<int>();
if (this.Request.IsAjaxRequest())
{
return PartialView(model);
}
return View(model);
}

I see one problem in the code above:
The $.get() does not do anything when your request is complete(your data has been fetched from the server)
Instead of passing null there you should pass in a function with a parameter which is the data. Example:
$.get("/Home/Index"
, params,
function(data){
//do something with data.
//data is json object returned
}, "json");
in this function you can actually have your filter applied to the table

Related

Why does select2 return null?

I have a class "MetaKeyword" and an a class "Article", which has a List MetaKeywords atributes. These metakeywords are stored in db and users select them for their articles via select2 in html. But this article atribute returns null, even though rawValue in ModelState has values.
Here's my controller code:
[HttpGet]
public IActionResult Create(Guid Id)
{
var article = new Article();
var Page = _dataManager.Pages.GetPageById(Id);
var Blog = _dataManager.Blogs.GetBlogById(Id);
ViewBag.KeywordId = new SelectList(_dataManager.MetaKeywords.GetMetaKeywords(), "Id", "Name");
if ((Page == null) && (Blog == null))
return NotFound();
else
return View(article);
}
[HttpPost]
public IActionResult Create(Article article, IFormFile titleImageFile)
I didn't list HtppPost action here as it may not help in solving the issue
And that's my html part resposible for MetaKeywords:
<div>
<label asp-for="MetaKeywords" class="control-label">Keywords</label>
<select asp-for="MetaKeywords" id="metakeyword" name="metakeywords" style="width:250px" multiple asp-items=#ViewBag.KeywordId>
<option value=""> -- Select MetaKeywords --</option>
</select>
</div>
Also a script:
<script type="text/javascript">
jQuery.noConflict()(function ($) {
$(document).ready(function() {
$('#metakeyword').select2({
allowClear: true
});
});
});
</script>

Html.ActionLink is not working in foreach loop

I receive some data from another page. I try to loop through data and create a link. I get the data and put it in #Html.ActionLink(GroupID, "GroupActivity", "Home"). GroupID have value now.
But on screen it just shows the data but does not makes it a link.
<li>#Html.ActionLink("Timetable", "Timetable", "Home")</li>
<li>
<select class="form-control">
<option selected>Select Group</option>
#{ var GroupID = ""; }
#foreach (var item in Model)
{
<option>
#{
GroupID = item.GroupID.ToString();
ViewBag.SelectedGroup = GroupID;
}
#Html.ActionLink(GroupID, "GroupActivity", "Home")
</option>
}
</select>
</li>
enter image description here
You have to write there something like this:
Using Action link
#Html.ActionLink("Some text for link", "GroupActivity", "Home",new {GroupID=GroupID })
But in your case, this would not work because you are creating action link inside option which is invalid.
Using client side event (onchange)
$(function(){
$("#YourDropDownID").change(function(){
var selectedItem = $("#YourDropDownID option:selected").text();
var redirectURL = '#Url.Action("ActionName","ControllerName")';
window.location.href = redirectURL + "?item=" + selectedItem;
}
}

MVC 5 Layout page

I have an MVC site, and I use the same "_layout page" for all the view.
In _layout page, I have a select control.
What I want is to read the selected value of the control from the other pages.
Can you help me understand how to do?
Edit:
_Layout.cshtml
<div class="col-sm-4 col-xs-6">
<label class="col-sm-2 control-label" for="slt_Aziende">Azienda:</label>
<select id="mySharedSelectControl">
<option value="1">value 1</option>
<option value="2">value 2</option>
</select>
</div>
Index.cshtlm (using _Layout.cshtml)
#model IEnumerable<MySite.Models.MyModel>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
MyModelController
public class MyModelController : Controller
{
public ActionResult Index()
{
//get value from mySharedSelectControl from Layout page
var selectedValueFromLayoutPage;
//do something
return View();
}
}
Based on what #Mairaj said is right i.e you can't directly read values of controls in your controller.
What you can do is create a JavaScript function like this:
$(document).ready(function () {
$("#mySharedSelectControl").change(function () {
var dropdownValue = $(this).val();
$.ajax({
url: "#Url.Action("PutValueinSession", "MyModel")", //Action method on which you want to send this dropdown value
data: { id: dropdownValue },
success: function (e) {
window.location = window.location;
}
});
});
});
You can create a method in which you can put this value in session and used across your whole page like below:
public JsonResult PutValueinSession(int id)
{
Session["DropdownControlValue"] = id;
return Json(new { Result = "" }, JsonRequestBehavior.AllowGet);
}
Now you can access this value on any page:
public ActionResult Index()
{
//get value from mySharedSelectControl from Layout page
var selectedValueFromLayoutPage=Session["DropdownControlValue"];
//do something
return View();
}
You can't directly read value of controls in Controller, you need to send the value of dropdown to the controller and than process what you want.
Or you can directly read value of dropdown from JavaScript in other views and do your processing.

ASP MVC best method to search/return all values from database

In the case of a default value being used in an ASP MVC drown down list, I need the code to return all values or simply ignore that particular search criteria.
Below is the code I have in my View and Controller. Since the '%' does not seem to be working, is there another keyword/operator that will do the job?
View:
<form method="post">
<select name="Table" title="Table" style="font-size:8pt;">
<option value="%">--Table Name--</option>
<option value="AgentContEd">CE</option>
<option value="AgentProductTraining">PT</option>
</select>
<select name="IssueType" style="font-size:8pt;">
<option value="%">--Issue Type--</option>
<option value="W">Warning</option>
<option value="E">Error</option>
</select>
<select name="Status" style="font-size:8pt;">
<option value="%">--Status Type--</option>
<option value="O">Open</option>
<option value="U">Under Review</option>
</select>
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" style="padding-top: 0px;" />
</form>
Controller:
public ViewResult Index(FormCollection dropDownSelection)
{
//security
//if (!Security.IsViewer(User)) return RedirectToAction("Message", "Home", new { id = 2 });
//if (ViewBag.Level == 0) return RedirectToAction("Message", "Home", new { id = 2 });
string table = dropDownSelection["Table"];
string issue = dropDownSelection["IssueType"];
string status = dropDownSelection["Status"];
var followUpItem = from follow in db.FollowUpItems
where follow.TableName.Equals(table) &&
follow.IssueType.Equals(issue) &&
follow.Status.Equals(status)
select follow;
return View(followUpItem.ToList());
}
You can use either SqlMethods.Like or simply the String.Contains method. (Keep in mind that String.Contains will be problematic if you retain the use of % or any other SQL wildcards.)
So, the three variations would look like:
var followUpItem = from follow in db.FollowUpItems
where SqlMethods.Like(follow.TableName, table) &&
follow.IssueType.Contains(issue) &&
follow.Status.Equals(status)
select follow;
I haven't compiled this, but I'm guessing you want something like:
public ViewResult Index(FormCollection dropDownSelection)
{
//security
//if (!Security.IsViewer(User)) return RedirectToAction("Message", "Home", new { id = 2 });
//if (ViewBag.Level == 0) return RedirectToAction("Message", "Home", new { id = 2 });
string table = dropDownSelection["Table"];
string issue = dropDownSelection["IssueType"];
string status = dropDownSelection["Status"];
var followUpItem = from follow in db.FollowUpItems
where (follow.TableName.Equals(table) || table.Equals("%")) &&
(follow.IssueType.Equals(issue) || issue.Equals("%")) &&
(follow.Status.Equals(status) || status.Equals("%"))
select follow;
return View(followUpItem.ToList());
}

How can I call Ajax from Javascript?

I have a drop down list
<select onchange="alert(this.value);">
<option selected="selected" value="cat">cat</option>
<option value="dog">dog</option>
</select>
I would like to make it so that when the users changes a value then an AJAX call is sent to my MVC controller which then updates the database.
I've done this with forms but never from javascript. Does anyone have an example of how this could be done.
thanks,
If you are using jQuery:
<select id="category" name="category">
<option selected="selected" value="cat">cat</option>
<option value="dog">dog</option>
</select>
and then:
$(function() {
$('#category').change(function() {
$.post('/home/save', { selectedCategory: $(this).val() }, function(result) {
alert('success');
});
});
});
which will send an AJAX request to the following action:
[HttpPost]
public ActionResult Save(string selectedCategory)
{
// TODO: process the selected category
return Json(new { success = true });
}

Resources