How to use jQuery UI in ASP.NET MVC 5 - asp.net-mvc

I'm trying to create an autocomplete text box using Jquery UI.
I can see that GetActiveItems works fine and i got a json result , but I can't see the autocomplete on the screen. I think that the problam is in the 'OnActionExecuted' when the ActionResult is being execute.
Please help me :)
thanks,
Siri
View:
<input type="text" id="mpvalue" name="mpvalue" />
<script type="text/javascript">
$(document).ready(function () {
$('#mpvalue').autocomplete({
source: '#Url.Action("GetActiveItems")'
});
})
</script>
Controller:
public ActionResult GetActiveItems(string term)
{
var result = from e in db.Items
where (e.IsBlock != true) && (e.Description.ToLower().Contains(term))
select e.Description;
return Json(result, JsonRequestBehavior.AllowGet);
}

Related

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.

Kendo MVC multiple uploaders

I'm using the kendo controls with MVC. I have a basic uploader working, but I need to create them dynamically and handle that code on the back end. Here's my simple example that's working
<input name="attachments" type="file" id="attachments" />
<script type="text/javascript">
$(document).ready(function () {
$("#attachments").kendoUpload({
async: {
saveUrl: '#Url.Action("Save", "AppConfig")',
autoUpload: true
}
});
});
</script>
[HttpPost]
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
if (SaveUploadedFile(attachments, "Background"))
{
return Content("");
}
else
{
return Content("error");
}
}
However, what I need to do is create the ids dynamically and handle it on the backend. So this is how I'm making the file uploaders
#foreach (var item in Model) {
string fid = String.Format("{0}{1}", #item.fieldType, #item.appConfigId.ToString());
<input name="#fid" id="#fid" type="file" />
<script type="text/javascript">
$(document).ready(function () {
$("##fid").kendoUpload({
async: {
saveUrl: '#Url.Action("Save", "AppConfig")',
autoUpload: true
}
});
});
</script>
}
Now I get that the HttpPostedFileBase argument has to match your id of your html element, but I have no idea how to modify the code behind, so that I can take in multiple uploaders. Any ideas?
Why don't you just use the multiple functionality of the Uploader? It is enabled by default.

autocomplete in asp.net mvc (razor)

I'm trying to implement the autocomplete function in my website, but won't work properly.
Here is the code of my view:
<script src="~/Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#SearchString").autocomplete({
source: "/Test/AutocompleteSuggestions",
minLength: 1,
select: function (event, ui) {
if (ui.item) {
$("#SearchString").val(ui.item.value);
$("form").submit();
}
}
});
});
</script>
#using (Html.BeginForm())
{
<p>
Find by name: #Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
Here is code of my autoComplete controller action:
public JsonResult AutocompleteSuggestions(string searchstring)
{
var suggestions = from s in db.Students
select s.Name;
var namelist = suggestions.Where(n => n.ToLower().StartsWith(searchstring.ToLower()));
// return namelist.ToList();
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Can anyone help me ?
Thanks in advance
you are trying to pass IQueryable. try replacing it with
return Json(namelist.ToList(), JsonRequestBehavior.AllowGet);
if that still doesnt work.
try replacing "searchString" to "term"
public JsonResult AutocompleteSuggestions(string term)
Ive read an article that you must use the "term" query string. but Im not pretty sure about it.

ASP.Net MVC - Ajax.BeginRequest() not generating an ajax request

This is my Test.cshtml:
#using(Ajax.BeginForm("Test", new AjaxOptions()))
{
<p>
Some String: <input name="someString" type="text" />
</p>
<button type="submit">Submit</button>
}
Where jquery-1.4.4.min.js is included by the layout.
My Controller has the following two actions:
public ActionResult Test()
{
return View();
}
[HttpPost]
public ActionResult Test(string someString)
{
if (Request.IsAjaxRequest())
return Json("Okey-dokey");
return View();
}
It seems that when I hit submit, it always does a full post-back, Request.IsAjaxRequest() is never true!
What gives?
George,
Please make sure that you include the script jquery.unobtrusive-ajax.js in your layout page.
counsellorben
I see no ajax functionality in your code examples.
You need to use Something like this to get ajax functionality
using (Ajax.BeginForm("Test", "ControllerName" ,null,
new AjaxOptions { OnComplete = "FunctionToCallOnSuccess" }))
It is post, indeed.
You should use AJAX call, like this:
$(function(){
$( "#myButton" ).click(function(){
$.getJSON("/Controller/Test", {someString: $("#someString").val()}, function(data){
alert(data);
}
});
});
and in your form:
<p>
Some String: <input name="someString" id="someString" type="text" />
</p>
<button type="button">Submit</button>
This should work.

How do you close an ASP.NET MVC page from the controller?

I have an ASP.NET MVC app that opens a "Request" view in a new browser window. When the user submits the form, I'd like the window to close. What should my RequestController code look like to close the window after saving the request information? I'm not sure what the controller action should be returning.
You could return a View that has the following javascript (or you could return a JavaScript result) but I prefer the former.
public ActionResult SubmitForm()
{
return View("Close");
}
View for Close:
<body>
<script type="text/javascript">
window.close();
</script>
</body>
Here is a way to do it directly in your Controller but I advise against it
public ActionResult SubmitForm()
{
return JavaScript("window.close();");
}
Like such:
[HttpPost]
public ActionResult MyController(Model model)
{
//do stuff
ViewBag.Processed = true;
return View();
}
The view:
<%if(null!=ViewBag.Processed && (bool)ViewBag.Processed == true){%>
<script>
window.close();
</script>
<%}%>
It sounds like you could return an almost empty View template that simply had some javascript in the header that just ran "window.close()".
You can close by this code:
return Content(#"<script>window.close();</script>", "text/html");
This worked for me:
[HttpGet]
public ActionResult Done()
{
return Content(#"<body>
<script type='text/javascript'>
window.close();
</script>
</body> ");
}
This worked for me to close the window.
Controller:
return PartialView("_LoginSuccessPartial");
View:
<script>
var loginwindow = $("#loginWindow").data("kendoWindow");
loginwindow.close();
</script>
Using this you can close the window like this:
return Content("<script language='javascript'>window.close();</script>");

Resources