Partial View not working propely in index view. - javascript

I am developing MVC application and using razor syntax.
In this application I am giving comment facility.
I have added a partial view, which loads the comment/Records from DB.
In below image, we can see the comment box which is called run-time for employee index view.
Now as we can see comment box, I called at run-time, which is partial view, but problem is I can add comment for only on first record...after first record that button wont work at all...
anything is missing ?
Is there separate process when we call any partial view run-time and make in action on it ?
See the pic...
Here is the code....
#model PagedList.IPagedList<CRMEntities.Customer>
<link href="../../Content/Paging.css" rel="stylesheet" type="text/css" />
<link href="../../Content/EventEntity.css" rel="stylesheet" type="text/css" />
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")%>" type="text/javascript"></script>
<div id="ListBox">
<div id="ListHeader">
All customers(#Model.TotalItemCount)
</div>
#foreach (var item in Model)
{
<div id="ListContent">
<span class="ContentTitleField">#Html.ActionLink(item.Name, "Details", new { id = item.Id }, new { #style="color:#1A6690;" })</span>
#if (item.Owner != null)
{
<span class="ContentSecondaryField">#Html.ActionLink(item.Owner.FullName, "Details", "Employee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
}
<span class="ContentSecondaryField">#Html.DisplayFor(modelItem => item.Address)</span>
<span id="flagMenus">
#Html.Action("ShowFlag", "Flagging", new { entityId=item.Id, entityType="Customer"})
</span>
#if (item.Opportunities.Count > 0)
{
<span class="FlagOpportunity">#Html.ActionLink("opportunities(" + item.Opportunities.Count + ")", "Index", "Opportunity", new { custid = item.Id }, new { #style = "color:#fff;" })</span>
}
<div style="float:right;">
#Html.Action("SetRate", "Rating", new { entityId = item.Id, rating = item.Rating, entityname = "Customer" })
</div>
<div id="subscribeStatus" style="float:right;">
#Html.Action("ShowSubscribedStatus", "Subscribing", new { entityId = item.Id, entityType = "Customer" })
</div>
<div class="ListLinks">
<span class="ListEditLinks">
<span style="float:left;">#Html.ActionLink("edit", "Edit", new { id = item.Id })</span>
<span class="LinkSeparator"></span>
</span>
<span class="ListAddLinks">
<span style="float:left;">#Html.ActionLink("+opportunity", "Create", "Opportunity", new { custid = item.Id }, null)</span>
<span class="LinkSeparator"></span>
<span>#Ajax.ActionLink("+Comment", null, null, null, new { id = item.Id, #class = "addremark" })</span>
</span>
<div class="RemarkBox"></div>
</div>
<span class="CommentAdd">
</span>
<div class="CommentBlock">
</div>
<span>#Ajax.ActionLink("Add Comment", null, null, null, new { id = item.Id, #class = "addremark" })</span>
</div>
}
<div class="PagingBox">
#Html.Action("CreateLinks", "Pager", new { hasPreviousPage = Model.HasPreviousPage, hasNextPage = Model.HasNextPage, pageNumber = Model.PageNumber, pageCount = Model.PageCount })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.RemarkBox').hide();
$('a.addremark').click(function () {
var url="#Html.Raw(Url.Action("ShowCommentBox", "Comment", new { Id = "idValue", EntityType = "Customer" }))";
url=url.replace("idValue",event.target.id);
$('.RemarkBox').load(url);
$(this).closest('div').find('div.RemarkBox').slideToggle(300);
return false;
});
$("a.pagenumber").click(function () {
var page = 0;
page = parseInt($(this).attr("id"));
$.ajax({
url: '#Url.Action("GetPagedCustomers")',
data: { "page": page },
success: function (data) { $("#customerlist").html(data); }
});
return false;
});
});
</script>

To expand on what Alberto León is saying, the partial page load will not cause the document ready event to fire, so the re-rendered elements will not have the javascript event handlers registered after the first comment is added.
To resolve this, you could put the event registration code into a function, and call this both from the document ready event and the success handler of the AJAX call. Something like this:
function AssignEventHandlers() {
$('a.addremark').click(function () {
....
});
$("a.pagenumber").click(function () {
var page = 0;
page = parseInt($(this).attr("id"));
$.ajax({
url: '#Url.Action("GetPagedCustomers")',
data: { "page": page },
success: function (data) {
$("#customerlist").html(data);
AssignEventHandlers();
}
});
return false;
});
}
$(document).ready(function () {
$('.RemarkBox').hide();
AssignEventHandlers();
}

In success function you need to recall the javascript, or the jquery code that makes the button work. Is an error that taked me a lot of time. Anything uploaded by ajax or any renderpartiAl needs to recall javascript.
$('.RemarkBox').load(url, function() {
//RECALL JAVASCRIPT
});

Related

Knockout JS How to Access a Value from Second View Model / Binding

I am new to Knockout JS and think it is great. The documentation is great but I cannot seem to use it to solve my current problem.
The Summary of my Code
I have two viewmodels represented by two js scripts. They are unified in a parent js file. The save button's event is outside
both foreach binders. I can save all data in the details foreach.
My Problem
I need to be able to include the value from the contacts foreach binder with the values from the details foreach binder.
What I have tried
I have tried accessig the data from both viewmodels from the parent viewmodel and sending the POST request to the controller from there but the observeableArrays show undefined.
Create.CSHTML (Using MVC5 no razor)
<div id="container1" data-bind="foreach: contacts">
<input type="text" data-bind="value: contactname" />
</div>
<div data-bind="foreach: details" class="card-body">
<input type="text" data-bind="value: itemValue" />
</div>
The save is outside of both foreach binders
<div class="card-footer">
<button type="button" data-bind="click: $root.save" class="btn
btn-success">Send Notification</button>
</div>
<script src="~/Scripts/ViewScripts/ParentVM.js" type="text/javascript"></script>
<script src="~/Scripts/ViewScripts/ViewModel1.js" type="text/javascript"></script>
<script src="~/Scripts/ViewScripts/ViewModel2.js" type="text/javascript"></script>
ViewModel1
var ViewModel1 = function (contacts) {
var self = this;
self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
return {
contactName: contact.contactName
};
}));
}
ViewModel2
var ViewModel2 = function (details) {
var self = this;
self.details = ko.observableArray(ko.utils.arrayMap(details, function (detail) {
return {
itemNumber: detail.itemValue
};
}));
}
self.save = function () {
$.ajax({
url: baseURI,
type: "POST",
data: ko.toJSON(self.details),
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
window.location.href = "/Home/Create/";
},
error: function (error) {
console.log(error);
window.location.href = "/Homel/Create/";
}
});
};
ParentViewModel
var VM1;
var VM2;
var initialContactInfo = [
{
contactPhone: ""
}
]
var initialForm = [
{
itemValue: ""
]
}
$(document).ready(function () {
if ($.isEmptyObject(VM1)) {
ArnMasterData = new ViewModel1(initialContactInfo);
ko.applyBindings(VM1, document.getElementById("container1"));
}
if ($.isEmptyObject(VM2)) {
VM2 = new ViewModel2(initialForm);
ko.applyBindings(VM2, document.getElementById("container2"));
}
});

Dropzone instance works on first element but not cloned elements (Vue)

I have a snippet below which is essentially my entire code block at this point, and essentially it creates a div and when you click "add another zone" it will clone that div. This allows the user to enter multiple lines of info and each have their own result and image.
The issue is that I'm successfully cloning everything with it's own unique identity thanks to my card setup. However, dropzone is not replicating. The first file dropzone form will work perfectly, but when I clone the div and have 2 or more dropzone insnstances on the page they don't work (they don't show the upload image text or anything)
How can I successfully apply my same logic to the dropzone instance here?
new Vue({
components: {},
el: "#commonNameDiv",
data() {
return {
searchString: [''],
results: [],
savedAttributes: [],
cards: [],
showList: false,
zoneNumber:[],
imageZoneNames: [] }
},
methods: {
autoComplete(ev, card) {
this.results = [];
console.log(this.searchString);
if (ev.target.value.length > 2) {
axios.get('/product/parts/components/search', {
params: {
searchString: ev.target.value
}
}).then(response => {
card.results = response.data;
this.showList = true;
console.log(this.results);
console.log(this.searchString);
});
}
},
saveAttribute(result, card) {
card.value = result.attribute_value;
card.results = [];
card.zone = this.zoneNumber;
this.showList = false;
},
addCard: function() {
this.cards.push({
index: "",
value: "",
zoneNumber: "",
results: [],
componentImage:""
});
console.log(this.cards);
},
hideDropdown() {
this.showList = false;
},
},
created() {
this.addCard();
let instance = this;
Dropzone.options = {
maxFilesize: 12,
renameFile: function (file) {
var dt = new Date();
var time = dt.getTime();
return time + file.name;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
removedfile: function (file) {
console.log(file.upload.filename);
var name = file.upload.filename;
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
},
init: function() {
this.on("addedfile",
function(file) {
instance.imageZoneNames.push({name: file.upload.filename, desc: 'Line Drawing'});
console.log(file);
console.log(instance.imageZoneNames);
});
}
};
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.0/dropzone.js"></script>
<div id="commonNameDiv">
<div class="uk-grid" v-for="(card, i) in cards" :key="i">
<div class="uk-width-1-10" >
<input v-model=" card.zoneNumber" size="4" type="text" name="mapNumber">
</div>
<div class="uk-width-6-10">
<input
style="width:100%"
placeholder="what are you looking for?"
v-model="card.value"
v-on:keyup="autoComplete($event, card)"
>
<div v-if="showList" class="panel-footer componentList" v-if="card.results.length">
<ul>
<li v-for="(result, i) in card.results" :key="i">
<a v-on:click="saveAttribute(result, card)">#{{ result.attribute_value }}</a>
</li>
</ul>
</div>
</div>
<div class="uk-width-3-10">
<form method="post" action="{{url('product/parts/upload/store')}}" enctype="multipart/form-data"
class="dropzone">
</form>
</div>
</div>
<div style="height: 35px;">
</div>
<div>
<a v-on:click="addCard">Add another zone</a>
</div>
</div>
When you instantiate the Dropzone class, it automatically looks for elements to transform in dropzones (by default, elements with the .dropzone class).
It looks like you want to dynamically add elements that are dropzones. Then you need to trigger the dropzone transformation yourself.
I would suggest you disable the autoDiscover option, and manually designates each element you want to transform into dropzones :
addCard() {
this.cards.push({
...
});
let cardIndex = this.cards.length - 1;
// Waiting for the element #dropzone-X to exist in DOM
Vue.nextTick(function () {
new Dropzone("#dropzone-"+cardIndex, {
...
});
});
},
created() {
...
Dropzone.autoDiscover = false
// no new Dropzone()
...
// Starting setup
this.addCard();
},
<form ... class="dropzone" v-bind:id="'dropzone-'+i">
Working jsbin
There are several ways to select the element to transform ($refs, ids, classes), here I'm suggesting ids.
See the doc on programmatically creating dropzones
Actually it is being created, but the Dropzone is not being reconstructed.
I think you have to create a new instance of the Dropzone.
if you try to insert:
created() {
this.addCard();
var myDropzone = new Dropzone('.dropzone')
let instance = this;
Dropzone.options.myDropzone = {
or even add the options to the addCard method or set a setupDropzones method and add it to the addCard method.

Can't render template into div

I need to render my template templates/page.html:
<section class="section">
<div class="container">
<h1 class="title"><%= title %></h1>
<div><%= content %></div>
<div><%= pages %></div>
</div>
</section>
into my div element with page-content id:
// Underscore mixins
_.mixin({templateFromUrl: function (url, data, settings) {
var templateHtml = "";
this.cache = this.cache || {};
if (this.cache[url]) {
templateHtml = this.cache[url];
} else {
$.ajax({
url: url,
method: "GET",
async: false,
success: function(data) {
templateHtml = data;
}
});
this.cache[url] = templateHtml;
}
return _.template(templateHtml, data, settings);
}});
// Models
var PageState = Backbone.Model.extend({
defaults: {
title: "",
subtitle: "",
content: "",
pages: "",
state: "games"
}
});
var pageState = new PageState();
// Routers
var PageRouter = Backbone.Router.extend({
routes: {
"": "games",
"!/": "games",
"!/games": "games",
"!/users": "users",
"!/add-user": "add_user"
},
games: function () {
select_item($("#games"));
console.log("games");
pageState.set({ state: "games" });
},
users: function () {
select_item($("#users"));
console.log("users");
pageState.set({ state: "users" });
},
add_user: function () {
console.log("add_user");
}
});
var pageRouter = new PageRouter();
// Views
var Page = Backbone.View.extend({
templates: {
"page": _.templateFromUrl("/templates/page.html")
},
initialize: function () {
this.render();
},
render: function () {
var template = this.templates["page"](this.model.toJSON());
this.$el.html(template);
return this;
}
});
$(function () {
var page = new Page({
el: '#page-content',
model: pageState
});
});
// Run backbone.js
Backbone.history.start();
// Close mobile & tablet menu on item click
$('.navbar-item').each(function(e) {
$(this).click(function() {
if($('#navbar-burger-id').hasClass('is-active')) {
$('#navbar-burger-id').removeClass('is-active');
$('#navbar-menu-id').removeClass('is-active');
}
});
});
// Open or Close mobile & tablet menu
$('#navbar-burger-id').click(function () {
if($('#navbar-burger-id').hasClass('is-active')) {
$('#navbar-burger-id').removeClass('is-active');
$('#navbar-menu-id').removeClass('is-active');
} else {
$('#navbar-burger-id').addClass('is-active');
$('#navbar-menu-id').addClass('is-active');
}
});
// Highlights an item in the main menu
function select_item(sender) {
$("a.v-menu-item").removeClass("is-active");
sender.addClass("is-active");
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<body>
<section class="hero is-primary is-medium">
<div class="hero-head">
<nav id="navMenu" class="navbar">
<div class="container">
<div class="navbar-brand">
<a class="navbar-item is-size-2">Virto</a>
<span id="navbar-burger-id" class="navbar-burger burger" data-target="navbar-menu-id">
<span></span>
<span></span>
<span></span>
</span>
</div>
<div id="navbar-menu-id" class="navbar-menu">
<div class="navbar-end">
<a id="games" href="#!/games" class="navbar-item v-menu-item is-active">Games</a>
<a id="users" href="#!/users" class="navbar-item v-menu-item">Users</a>
<span class="navbar-item">
<a href="#!/add-user" class="button is-primary is-inverted">
<span class="icon">
<i class="fas fa-user-circle"></i>
</span>
<span>Add user</span>
</a>
</span>
<div>
</div>
</div>
</nav>
</div>
</section>
<div id="page-content"></div>
</body>
But my content doesn't load... I'm a noobie in backbone.js still so can someone explain what do I doing wrong and how to fix?
ADDED
I have checked my script in debugger. It loads a template and finds my div in the render() function but I can't see any result in browser after, my div is empty still.
I created a plunker with your code, and it works fine for me: link
I think you only forgot to initialize your model:
// Models
var PageState = Backbone.Model.extend({
defaults: {
title: "Title - 1",
subtitle: "Subtitle - 1",
content: "Content",
pages: "1",
state: "games"
}
});

Get data from textbox to pass to controller without refreshing page/submitting form in MVC

Right now, on my page I have a button at the top of one of my views <button type="button" id="show">Find Project</button> that when pressed, renders a partial view (which is a table) at the bottom of the page. My layout is formatted as:
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<!--this is my navbar-->
</div>
<div class="container body-content">
#RenderBody()
</div>
<div class="wrapper">
<!-- TABLE WILL APPEAR HERE -->
</div>
</body>
The javascript that makes the table appear is:
$(document).ready(function() {
$("#show").on("click", function() {
$.ajax({
url: '/Projects/SearchTable',
type: "GET"
}).done(function(partialViewResult) {
$(".wrapper").html(partialViewResult);
$(".wrapper").css('display', 'block');
});
});
});
/Projects/SearchTable is the controller action that renders the partial view:
[HttpGet]
public ActionResult SearchTable()
{
var states = GetAllStates();
var model = new ProjectClearanceApp.Models.ProjectViewModel();
model.States = GetSelectListItems(states);
model.Projects = from m in db.Projects select m;
return PartialView("~/Views/Projects/_ClearedProjects.cshtml", model);
}
The text boxes are dispersed throughout my main view, and all appear in the same format:
<div class="col-md-5 entry-field">
#Html.LabelFor(model => model.Project.FirstNamedInsured, htmlAttributes: new { #class = "control-label" })
#Html.TextBoxFor(model => model.Project.FirstNamedInsured, new { #class = "form-control text-box single-line", maxlength=150 })
#Html.ValidationMessageFor(model => model.Project.FirstNamedInsured, "", new { #class = "text-danger" })
</div>
Except for two dropdowns that are formatted like so:
<div class="col-md-3 address-info">
#Html.LabelFor(m => m.Project.FirstNamedInsuredAddress.State, htmlAttributes: new { #class = "address-label" })
#Html.DropDownListFor(m => m.Project.FirstNamedInsuredAddress.State,
Model.States,
"--",
new { #class = "form-control address-entry" })
#Html.ValidationMessageFor(model => model.Project.FirstNamedInsuredAddress.State, "", new { #class = "text-danger" })
</div>
where Model.States is an enumerable to populate the drop down list with all of the states.
Is it possible to get the data from those textboxes and pass them as data/arguments to the controller for use in the partial view without submitting a form or refreshing the page?
Send the parameter like this:
public ActionResult SearchTable(string firstNamedInsured)
{
//Use the parameter in the model or any where
var states = GetAllStates();
var model = new ProjectClearanceApp.Models.ProjectViewModel();
model.States = GetSelectListItems(states);
model.Projects = from m in db.Projects select m;
return PartialView("~/Views/Projects/_ClearedProjects.cshtml", model);
}
And javascript:
$(document).ready(function () {
$("#show").on("click", function () {
$.ajax({
url: '/Projects/SearchTable?firstNamedInsured=' + $('#' + #Html.IdFor(m => m.Project.FirstNamedInsured)).val(),
type: "GET"
}).done(function (partialViewResult) {
$(".wrapper").html(partialViewResult);
$(".wrapper").css('display', 'block');
});
});
});

How to do autocomplete using values from the database in MVC 5?

At the moment, I have the following code:
main.js:
$(function () {
var keys = ["test1", "test2", "test3", "test4"];
$("#keywords-manual").autocomplete({
minLength: 2,
source: keys
});
});
Test.cshtml:
#model App.Models.Service
#{
ViewBag.Title = "Test";
}
<script src="~/Scripts/main.js"></script>
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
#using (Html.BeginForm("SaveAndShare", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<h4>Create a new request.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.ServiceType, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.ServiceType, new { #class = "form-control", #id = "keywords-manual" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit!" />
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The point is that currently I have just provided 4 constant values to the autocomplete. But then I created a database and a table named "services", which comes from my model named Service. I have already provided a few rows to the table with values. I have a field in my table called ServiceType, and I want the autocomplete to take the values of that column as a source. Please note that I have hosted my database in Azure and it is MySQL, though, I think it doesn't matter here. Can you tell me how can I take as a source the values of ServiceType column that is located inside my services table?
As far as I can tell by your question, it should look something like this:
$("#keywords-manual").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/GetServiceTypes",
data: "{ 'keywords': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id
}
}))
}
});
},
minLength: 2
});
And the controller,
YourContext db = new YourContext();
public JsonResult GetServiceTypes() {
db.ServiceType.Where(s => keywords == null || s.Name.ToLower()
.Contains(keywords.ToLower()))
.Select(x => new { id = x.ServiceTypeID, value = x.ServiceTypeName }).Take(5).ToList();
return result;
}
Apologies for any typos, but that should be the jist of it. If you need to be searching for more than one keyword, in the controller method, split the value from 'keywords-manual' into a string array, then use a foreach loop or similar approach to match each value, adding matches to a total list each time.
** I say string array, that's pretty oldschool, split it into a list :)

Categories