ASP.NET MVC -Refresh CodeMirror editor onclick - javascript

I have a codemirror editor in a partial view and a list of files in the main view. I want to refresh the editor once a file name is clicked. I tried many solutions provided on StackOverflow and other websites but nothing worked , and This is my first time using Javascript so I can't figure out What am I doing wrong.
This is my code:
Controller:
public ActionResult Index()
{
StudentsCodes model = new StudentsCodes();
model.Student = (Student)CurrentUser;
var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
model.Instructor =(Instructor) user;
return View(model);
}
public PartialViewResult DevelopmentPartial (StudentsCodes path )
{
return PartialView(path);
}
Main view:
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.js"></script>
<ul id="tree">
#foreach (var file in Directory.GetFiles(Server.MapPath("~/Content/" + Model.Student.UserName + "/CompilerProject/" + name)))
{
var filename = Path.GetFileName(file);
<li id="filelist" onclick="#(Model.path = "~/Content/" + Model.Student.UserName + "/CompilerProject/src/" + #filename)">
<span class="glyphicon glyphicon-file"></span>
#filename
/li>
}
<div id="partial">
#{
Html.RenderPartial("DevelopmentPartial",null);
}
</div>
<script>
$(document).ready(function () {
$("#filelist").click(function (e) {
#{Html.RenderAction("DevelopmentPartial", Model);
}
});
});
</script>
partial view:
#using (Html.BeginForm())
{
var fileContents= "";
if (Model==null)
{
fileContents = "";
}
else
{
fileContents = System.IO.File.ReadAllText(Server.MapPath(Model.path));
}
#Html.TextArea("code", fileContents, new { id = "code" })
}
I can't assign ids for list elements since their number is unknown at compile time and it changes when the user adds or deletes a file, that's why most of the solutions provided didn't work . The result here was 3 editors overlapping and display the contents of the last file. And <li> items are non-clickable. What am I doing wrong in my code ?
Edit:
After updating the script as the following:
<script>
$(document).ready(function() {
$(".filelist").on("click",function (e) {
$("#partial").load('DevelopmentPartial');
});
});
</script>
It refreshes the partial view but the editor is always empty, and the Model is always null. Is it wrong to update the Model using "onclick"?

In case someone faced the same problem, I solved it by changing id to class at the list, then by using this script:
<div id="partial">
#{
Html.RenderAction("DevelopmentPartial", new { path1 = Model.path});
}
</div>
<script>
$(document).ready(function () {
$('.filelist').on('click', function (e) {
alert('Im clicked on filePath = ' + $(this).attr('value'));
var filePath = $(this).attr('value'); //value is attribute set in Html
$('#partial').load('DevelopmentPartial', { path1: filePath });
});
});
</script>
And the controller:
public PartialViewResult DevelopmentPartial(string path1)
{
modelSC.path = path1;
return PartialView(modelSC);
}
where modelSC is a global variable in the controller.

Related

How to add a clear button in jquery autocomplete(mvc razor)

I have a search functionality which already works by searching the data that the user requests. I would like to add a clear button for the user to be able to clear the search bar, at the moment the user has to clear the search using the "backspace" button and press "enter to go back the page with all the data. I am a expert in front end so would appreciate some help thank you in advance.
Javascript
$(function () {
$("#SearchString").autocomplete({
source: '#Url.Action("GetUserJSON")',
minLength: 1
})
});
$(function () {
$("#SearchString").focus();
});
$(function () ) {
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close');
});
};
Razor HTML
#using (Html.BeginForm("Index", "User", FormMethod.Get, null))
{
<div class="search-wrap">
#Html.TextBoxFor(m => m.SearchString, new { id = "SearchString", #class = "lookup txt-search js-autocomplete-submit", #placeholder = "Search", #type ="search" })
#*<img src="~/Content/Images/close.png" id ="closebutton"/>*#
<button type="button" id="clearbutton">Click Me!</button>
<i onclick="submitform()" class="btn-search fa fa-search"></i>
</div>
}
C# Class where data get pull from
public JsonResult GetUserJSON(string term)
{
var stores = (from st in UserLogic.GetUserIndex(1, term).IndexList
select new { st.Username, st.FirstName, st.LastName }).ToList();
List<String> returnList = new List<string>();
foreach (var item in stores)
{
if (item.Username.ToString().ToUpper().StartsWith(term.ToUpper()))
{
returnList.Add(item.Username.ToString());
}
else if (item.FirstName.ToUpper().Contains(term.ToUpper()))
{
returnList.Add(item.FirstName);
}
else if (item.Username.ToUpper().Contains(term.ToUpper()))
{
returnList.Add(item.Username);
}
}
returnList = returnList.Distinct().OrderByAlphaNumeric(s => s).ToList();
return Json(returnList, JsonRequestBehavior.AllowGet);
}
I think this is what you need:
$(function () {
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close');
$("#SearchString").val("")
});
});
Add $("#SearchString").val("") to your clearbutton click event
Edit:
You have mistyped the function for clearSearch
this is working example
please try using this
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close').val('');
});

Loading partial view depending on dropdown selection in MVC

I apologize I am still fairly new to MVC. I currently have a dropdownlist with some options. What I would like to do is depending on the dropdownlist value that I select then I should be able to render a partial view. I want the partial view to load as soon as the user selects from the dropdownlist.
Also, I am able to render my partial view but it's not returning what I need. When I select from the dropdownlist it does not take the functionID..it just returns all of the items regardless of the functionID.
I want the partial view to render based off the functionID.
Thank you very much. Any help is very much appreciated it.
Main View
#Html.DropDownListFor(m => m.FunctionID, new
SelectList(Model.functionList, "FunctionID", "Name"), "Select
Function", new {#id="id"})
<div id="partialPlaceHolder">
</div>
Partial View
#foreach (var items in Model.itemTypeList)
{
<pre> #items.Definitions</pre>
}
Controller
[HttpGet]
public ActionResult ViewOverview()
{
List<Function> functionList;
List<ItemType> itemTypeList;
using (BusinessLogic BLL = new BusinessLogic())
{
functionList = BLL.GetFunctionList();
itemTypeList = BLL.GetItemTypesList();
}
Words viewModel = new Words();
MetricDefinitions(viewModel);
return View(viewModel);
}
[HttpGet]
public ActionResult GetWords()
{
List<Function> functionList;
List<ItemType> itemTypeList;
using (BusinessLogic BLL = new BusinessLogic())
{
functionList = BLL.GetFunctionList();
itemTypeList = BLL.GetItemTypesList();
}
Words viewModel = new Words()
{
itemTypeList = itemTypeList,
functionList = functionList
};
return PartialView("_ViewWords", viewModel);
}
private void MetricDefinitions(Words model)
{
List<Function> functionList;
List<ItemType> itemTypeList;
using (BusinessLogic BLL = new BusinessLogic())
{
functionList = BLL.GetFunctionList();
itemTypeList = BLL.GetItemTypesList();
}
model.functionList = functionList;
model.itemTypeList = itemTypeList;
}
javascript
$(document).ready(function () {
$('#id').change(function () {
var selectedID = $(this).val();
$.get('/Home/GetWords/' + selectedID, function (data) {
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
});
I have added NetFiddle. It works here
Can you try to add selectedItem param into action and use jquery .load() function to get partial result into your target element.
[HttpGet]
public ActionResult GetWords(int selectedItem) // add your selectedVal value in controller
{
.....
}
jquery
// it is going to parse partial view into target div
$("#id").on("change", function(){
var url = '#Url.Action("GetWords", "Home")' + "?selectedItem=" + $(this).val();
$("#partialPlaceHolder").load(url, function(){
console.log("It worked");
$('#partialPlaceHolder').fadeIn('fast');
})
})

Javascript plugin needs to call back to client's Javascript

I am working on a plugin that allows to add an item to the shopping cart. The plugin is mine, and the shopping cart belongs to the customer. The idea is to add my plugin with a few lines of code to configure.
Once an item is bought, I need to call a function on the customer page so it can be added to the cart, but I didn't manage.
I have this code:
<script type="text/javascript">
$(document).ready(function () {
//plugin1.CallBackTest;
});
var plugin1 = new function() {
this.CallBackTest = function (str) {
console.log("callback in class");
FunctionIWantToCall(str);
}
}
function FunctionIWantToCall(str) {
console.log("callback on client " + str);
}
</script>
<div class="htmlcreatedbyplugin">
<button onclick="CallBackTest('something')">send back</button>
</div>
if I change this line to
send back
it will work, but this html is generated through the plugin class, and I don't know how to retrieve the name of the variable.
The customer should be able to tell the plugin which function to call, e.g
plugin1.AddToCartFunction = FunctionIWantToCall;
Any ideas?
Thank you Stavros Angelis, it works:
<script type="text/javascript">
$(document).ready(function () {
plugin1.CallBackFunction = "FunctionIWantToCall";
});
var plugin1 = new function () {
var myplugin = this;
this.CallBackFunction = "";
this.CallBackTest = function () {
console.log("callback in class");
var item = JSON.parse($(this).attr("vals"));
if (myplugin.CallBackFunction != "") {
window[myplugin.CallBackFunction](item);
}
}
function BindCartButtons() {
console.log("binding buttons")
$(document).on("click", ".htmlcreatedbyplugin > button", myplugin.CallBackTest);
}
BindCartButtons();
}
function FunctionIWantToCall(item) {
console.log("callback on client " + item.id);
}
</script>
<div class="htmlcreatedbyplugin">
<button type="button" vals="{"id":12345, "color":"blue"}">Buy Me</button>
</div>

MVC 5, Ajax, Jquery - script works only once

<script>
$(function () {
var ajaxSubmit = function () {
var $form = $(this);
var settings = {
data: $(this).serialize(),
url: $(this).attr("action"),
type: $(this).attr("method")
};
$.ajax(settings).done(function (result) {
var $targetElement = $($form.data("ajax-target"));
var $newContent = $(result);
$($targetElement).replaceWith($newContent);
$newContent.effect("slide");
});
return false;
};
$("#search-form").submit(ajaxSubmit);
});
</script>
Ok, This script is for searching some content from databse. it works great, but only once. When im trying to hit submit again in my from, its not working again. Only when I refresh page.
Could someone help me?
My from in same index.cshtml file:
<div>
<form id="search-form" method="get" data-ajax="true" data-ajax-target="#zawartosc" data-ajax-update="#zawartosc">
<input id="search-filter" type="search" name="searchQuery"
data-autocomplete-source="#Url.Action("MiejscaPodpowiedzi", "Miejsce")"
placeholder="Wprowadź tekst, aby filtrować..." />
<input type="submit" id="send" value="Send" />
</form>
<div id="zawartosc">
#Html.Partial("_ListaMiejsc")
</div>
My controller:
public class HomeController : Controller
{
private DaneKontekst db = new DaneKontekst();
public ActionResult Index(string searchQuery = null)
{
var miejscaNaSwiecie = db.MiejscaNaSwiecie.Where(o => (searchQuery == null ||
o.NazwaMiejscaNaSwiecie.ToLower().Contains(searchQuery.ToLower()) ||
o.KrajMiejscaNaSwiecie.ToLower().Contains(searchQuery.ToLower()) ||
o.OpisMiejscaNaSwiecie.ToLower().Contains(searchQuery.ToLower()))).ToList();
var ViewModel = new HomeIndexViewModel()
{
MiejscaNaSwiecie = miejscaNaSwiecie
};
if (Request.IsAjaxRequest())
{
return PartialView("_ListaMiejsc", ViewModel);
}
return View(ViewModel);
}
Edited.
Because you are replacing the container. You should update only the content of that.
When you click for the first time, the response of the ajax call (the markup for the form) will replace the div (with id ="zawartosc"). So after this you do not have that div exist in your DOM any more. So your $targetElement is not going be the the container div (because it is gone !)
So instead of replacing the container div, simply update the content of that.
Replace
$($targetElement).replaceWith($newContent);
with
$($targetElement).html($newContent);
$($targetElement).html($newContent);
OR
$($targetElement).Load($newContent);

jquery dialog popup shown in the same window

I dont know whats wrong.
I follow this link http://www.dotnetcodesg.com/Article/UploadFile/2/286/CRUD%20operation%20using%20Modal%20Popup%20in%20ASP.NET%20MVC%204.aspx because need pretty same thing: CRUD grid with popup for edit.
I do everything inside HomeController and Index.cshtml which generated by VS2013.
I cut from the code the things involved:
Index.cshtml
grid.Column("", header: "Actions",
format: #<text>
#Html.ActionLink("Edit", "EditConstruct", new { id = item.Id, #class = "editDialog" })
<div id="dialog-edit" style="display: none">
Controller
public ActionResult EditConstruct(int id)
{
var data = advConstructRepository.Get(id);
AdvConstructModel model = new AdvConstructModel
{
Id = data.Id,
Description = data.Description,
MaintenanceTime = data.MaintenanceTime,
Location = data.Location,
Height = data.Height,
Width = data.Width,
MonthlyCost = data.MonthlyCost,
AdvConstructType = advConstructRepository.GetAdvConstructType(data.AdvTypeId)
};
ViewBag.IsUpdate = true;
return View("EditConstruct", model);
}
Edit View
#model AdvApplication.Models.AdvConstructModel
#{
Layout = null;
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
#using (Html.BeginForm("UpdateConstruct", "Home", "POST"))
{
#Html.ValidationSummary(true)
ViewBag.IsUpdate = true;
return View("EditConstruct", model);
}
etc...
But when i clicked on Edit action, i receive fields for edit but not in the popup, but on whole screen as a single page.
EditConstruct view was created as partial view.
Please suggest how to fix
It is probably the whole view being sent back, jquery deals in fragments, not whole pages.
Consider this change:
public ActionResult EditConstruct(int id)
{
var data = advConstructRepository.Get(id);
AdvConstructModel model = new AdvConstructModel
{
Id = data.Id,
Description = data.Description,
MaintenanceTime = data.MaintenanceTime,
Location = data.Location,
Height = data.Height,
Width = data.Width,
MonthlyCost = data.MonthlyCost,
AdvConstructType = advConstructRepository.GetAdvConstructType(data.AdvTypeId)
};
ViewBag.IsUpdate = true;
if(Request.IsAjaxRequest())
return PartialView("EditConstruct", model);
return View("EditConstruct", model);
}

Categories

Resources