Display a few lines of a text in MVC - javascript

I'm using MVC3 and wanna to display 3 lines of a Post in Blogging system and then add a link to go the rest of the post , you can see sample in most of blogs like this
this is my View :
#model IEnumerable<Blog.Web.UI.ViewModels.PostViewModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
#foreach (var item in Model)
{
<div>
<h3>
#Html.ActionLink(item.Title, "Post", "Blog", new { postId = item.Id, postSlug = item.UrlSlug }, null)
</h3>
</div>
<div>
<span>Category: </span>#item.Category
</div>
<div>
<span>Tag: </span>#item.Tag
</div>
<div>
#item.CreationDate.ToLongDateString()
</div>
<div>
#Html.DisplayTextFor(p => item.Body)
</div>
}
</div>
as it is shown
#Html.DisplayTextFor(p => item.Body)
shows whole of the post , but I wanna to do like the link I referenced , I think it is possible via javascript but I don't know How !

It looks like the example you provides trims off any extra text longer than a given length. You could do the same by modifying your ViewModel like so:
class PostViewModel
{
public string Body {get;set;}
public string ShortBody
{
get
{
return Body.Length <= 140
? Body
: Body.Substring(0, 140) + "...";
}
}
}
Then change your DisplayTextFor line to this:
#Html.DisplayTextFor(p => item.ShortBody)

Related

Dynamic table with 3 columns and dynamic rows in code behind mvc controller in c#

below shown is the table i needed. now i designed like
<div class="col-md-9">
#for (int i = 0; i < Model.CallList.Count(); i++)
{
<div class="col-md-4">
<input type="checkbox" id="cbLabelValue" value="#Model.CallList[i].LabelName" onclick="return javOpenPop()" />
<label for="c5option #Model.CallList[i].LabelAlias">#Model.CallList[i].LabelAlias</label><br />
</div>
}
</div>
in the view page.
What's the problem is when i changed the view from desktop to sm or xs devices all the content inside will come in a single line.
Can any one please tell that how to achieve it by writing html tags in code behind, appending to the view page by string builder
My Controller Code is
public ActionResult Index()
{
var callviewData = new CallView();
var getLabelValues = new ClickActionsViewModels();
getLabelValues.GetCallStatusValues();
List<ClickActionsViewModels> LabelDetails = new List<ClickActionsViewModels>();
foreach (var name in getLabelValues.GetLableName)
{
LabelDetails.Add(new ClickActionsViewModels()
{
LabelName = name.LabelName,
LabelAlias=name.LabelAlias
});
}
callviewData.CallList = LabelDetails;
return View(callviewData);
}
how to create here the responsive table here

Retrieve Firebase database specific value depending on key with angular 5

as the title says I build a CRUD application using Angular 5 and CRUD works just fine but now I need to retrieve a specific post data with advanced routing so the url should be something like :
https://example.com/blog/howtoDoSomething
and the page should contain this post details like name, content , image and so on .
I tried
details.component.ts
this.sub = this.route.params.subscribe(params => {
this.key = params['$key'];
});
details.component.html
<p>
this page about {{ $key }}
</p>
the above code worked fine with angular 4 with some difference of course and I used a json file not Firebase .
I also tried this one :
details.component.ts
var x = this.blogService.getData();
x.snapshotChanges().subscribe(item => {
this.blogList = [];
item.forEach(element => {
var y = element.payload.toJSON();
y["$key"] = element.key;
this.blogList.push(y as Blog);
});
});
details.component.html
<div *ngFor="let blog of blogList">
{{blog[$key].title}}
</div>
this one if I use blog alone like :
<div *ngFor="let blog of blogList">
{{blog}}
</div>
this retrieves the whole database as as
[object object] repeated
thanks in advance .
// user-service.ts
public getUser(userId: string) {
return this.afs.doc('users/' + userId).valueChanges();
)
// user-component.ts
// Get userId from route
this.user$ = this.userService.getUser(userId);
// user-component.html
<div *ngIf="user$ | async as user">
{{user | json}}
</div>

MVC 5 Razor view template binding hide script to a model radiobutton

Currently have a custom EditorTemplate which dynamically populates based on the incomming Model () in the Razor page.
The aim is to be able to hide the individual div 'Sub_Text' in the editor template based on the radio value.
Model: Prime.cs
public class Prime{
public List<QuestionModel> Questions { get; set; }
}
Model: QuestionModel.cs
public class QuestionModel{
public int Id { get; set; }
public string Question { get; set; }
public string Answer { get; set; }
public string SubText { get; set; }
}
Main View: _Reporting.cshtml
#model ViewModels.Prime
#for (int i = 0; i < Model.Questions.Count(); i++) //Dynamically generate and model bind database PolicyHolderKeyQuestions
{
#Html.EditorFor(x => x.Questions[i], "QuestionModel")
}
EditorTemplate: QuestionModel.cshtml
#model ViewModels.QuestionModel
#{
<div class="col-lg-2">
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.Yes)
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.No)
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.NA)
</div>
<div class="col-lg-9">
<div class="row">
<p>
<strong>#Model.Question</strong>
</p>
</div>
<div class="row" name="**Sub_Text**"> #* **Hide Me!** *#
#Model.SubText
</div>
</div>
}
So far the closest idea I have found is to add a script something like this to the bottom of the template:
<script type="text/javascript">
$(':radio[name=Answer').change(function () {
// read the value of the selected radio
var value = $(this).val();
var doc
if (value == 1) {
$('#Sub_Text').show();
}else{
$('#Sub_Text').hide();
}
});
</script>
Which seems to be able to work for something simpler without using #Html.EditorFor() in a loop.
It looks as if the script does not follow the same automatic naming changes as those that happen to the RadioButtonFor elements. Resulting in things like this:
Radio:
<input id="Questions_0__Answer" name="Questions[0].Answer" type="radio" value="No" />
While the divs and scripts keep referencing only what was directly entered.
How can you dynamically hide the "Sub_Text" div based on the radiobutton when it is nested in this way?
If there is a way to do this without feeding in a script per EditorFor radio group that would be even better, but all solutions are welcome.
Wrap the html generated by the EditorTemplate in a container so that you can use relative selectors
#model ViewModels.QuestionModel
<div class="question"> // container
<div class="col-lg-2">
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.Yes)
....
</div>
<div class="col-lg-9">
....
<div class="row">#Model.SubText</div>
</div>
</div>
and then the script can be
$(':radio').change(function () {
// get the associated element containing the SubText value
var row = $(this).closest('.question').find('.row');
if ($(this).val() == 1) {
row.show();
} else {
row.hide();
}
});
Side note: If your QuestionModel.cshtml is in the /Views/Shared/EditorTemplates or /Views/yourControllerName/EditorTemplates folder (which it should be) then the code in _Reporting.cshtml should be just
#model ViewModels.Prime
#Html.EditorFor(x => x.Questions)
No loop is required. The EditorFor() accepts IEnumerable<T> and generates the correct html for each item in the collection.

Filter my #html.dropdownlistfor

Im working with a project and i need to filter my second dropdownlistfor based on my first dropdownlistfor value. Its simple to understand but hard to code it since i dont know jquery or javascript and im working in mvc asp.net, aswell as using a database in sql server where the data is located.
I need to filter my dropdown for project based on my dropdown for customer.
here is some of the code:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>TimeEntry</legend>
<div class="editor-label">
#Html.Label("Customer")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.TimeEntry.CustomerId, #customerSelectList)
#Html.ValidationMessageFor(model => model.TimeEntry.CustomerId)
</div>
<div class="editor-label">
#Html.Label("Project")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.TimeEntry.ProjectId, #projectSelectList, "[ - No project - ]")
#Html.ValidationMessageFor(model => model.TimeEntry.ProjectId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
public IEnumerable<Customer> Customers { get; set; }
public IEnumerable<Project> Projects { get; set; }
here is a code which i think is the code that is calling from the database but not really sure:
var customers = service.GetAllCustomers().ToList();
model.Customers = new SelectList(customers, "CustomerId", "Name");
var projects = service.GetAllProjects().ToList();
model.Projects = new SelectList(projects, "ProjectId", "Name");
Okay so you have a controller with a method that gives you the filtered projects like so:
public class FilterController:Controller {
public ActionResult Projects(int customerId) {
// I expect this call to be filtered
// so I'll leave this to you on how you want this filtered
var projects = service.GetAllProjects().ToList();
// at this point, projects should already be filtered with "customerId"
return Json(new SelectList(projects, "ProjectId", "Name"),
JsonRequestBehavior.AllowGet);
}
}
Then you call that method on the client like this:
// when the customer dropdown changes, you want to use the selected value
// and filter the projects dropdown - more like refresh it
$("#TimeEntry_CustomerId").change(function(){
refreshProjects($(this).val());
});
function refreshProjects(id) {
var projects = $("#TimeEntry_ProjectId");
$.get('#Url.Action("projects","filter")', {customerId:id},
function (result) {
// clear the dropdown
projects.empty();
// rebuild the dropdown
$.each(result, function (i, e) {
projects.append($('<option/>').text(e.Text).val(e.Value));
});
});
}

How to dynamically create checkboxes OR multi select on MVC 4

In this project we have two list, one for the dealer and the second for his products.
So far if you check one dealer we get back all the product for this specific dealer, it implemented in javascript (Json).
Html (5 :)
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>DealerProduct</legend>
<div class="editor-label">
#Html.LabelFor(model => model.DealerID)
</div>
<div class="editor-field">
#Html.DropDownList("DealerID", String.Empty)
#Html.ValidationMessageFor(model => model.DealerID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductID)
</div>
<div class="editor-field">
#Html.DropDownList("ProductID", String.Empty)
#Html.ValidationMessageFor(model => model.ProductID)
</div>
<p>
<input type="submit" value="#Shared.Add" />
</p>
</fieldset>
}
JavaScript (Json :)
<script type="text/javascript">
$(document).ready(function()
{
$("#DealerID").change(function ()
{
var self = $(this);
var items="";
var url = "";
url = "#Url.Action("GetDealerProducts","DealerProduct")/"+self.val();
$.ajaxSetup({ cache: false });
$.getJSON(url,function(data)
{
$.each(data,function(index,item)
{
items+="<option value='"+item.Value+"'>"+item.Text+"</option>\n";
});
$("#ProductID").html(items);
$.ajaxSetup({ cache: true });
});
});
});
</script>
Controller :
public ActionResult GetDealerProducts(int id)
{
Dealer currentDealer = db.Dealers.Single(p => p.UserName == User.Identity.Name);
Dealer subDealer = db.Dealers.Single(s => s.DealerID == id);
List<Product> productOpenToSale = new List<Product>();
foreach (var item in currentDealer.ProductToSale)
if (!subDealer.ProductToSale.ToList().Exists(e => e.ProductID == item.ProductID))
productOpenToSale.Add(item.Product);
List<SelectListItem> productOpenToSaleList = new List<SelectListItem>();
productOpenToSale.ForEach(item => productOpenToSaleList.Add(new SelectListItem { Value = item.ProductID.ToString(), Text = item.ProductName }));
return Json(productOpenToSaleList, JsonRequestBehavior.AllowGet);
}
What I really need is adding (a pairing of) products dealer, which he can sell in the future.
Current option is to add products one by one, the desire is to give the possibility of multiple selection of all products.
Maybe something like dynamic checkBoxList or an foreach on a List from the ViewModel who add input - checkbox like this, but I don't know how to fill it after the dealer has selected on the first list and receive all the selected product back on submit..
10X for any help!! (&& sorry for my bad English :)
you can change this line of code
#Html.DropDownList("ProductID", String.Empty)
with something like this
<select id="SelectedItemIds" multiple="multiple" name="SelectedItemIds">
and having a viewModel on the server like this
class MyViewModel
{
public int[] SelectedItemIds { get; set; }
public int DealerID {get;set;}
}
and having a controller like this
[HttpPost]
public ActionResult Index(MyViewModel myViewModel)
{
return View();
}
I have similar situation and made it works here:
enter link description here
but I don't know how to pass the actual text back. I can only pass the index of selected items back to the controller. If you figure it out let me know.
Make sure your select name matches your variable name in the model.

Categories

Resources