Read More button in asp.net mvc3 - javascript

I am working on asp.net mvc3 application and have many records coming from database. I want to display only 10 records first then user can click on button to see next 10 records and so on. Like facebook wall posting more records. How can I implement this thing in my application ? I am using this to get 10 records but I want to display all records using more record button

This should get you going...
Assuming:
public class PostsViewModel
{
public IEnumerable<PostViewModel> Posts { get; set; }
}
Your controller might look like:
public class BlogController
{
public ActionResult Index()
{
PostsViewModel model = new PostsViewModel
{
Posts = postService.GetPosts(resultsPerPage: 10, page: 1)
};
return View(model);
}
public PartialViewResult More(Int32 page = 1)
{
PostsViewModel model = new PostsViewModel
{
Posts = postService.GetPosts(resultsPerPage: 10, page: page)
};
return PartialView(model);
}
}
And Views something like:
~/Views/Blog/Index.cshtml
#model PostsViewModel
#* Other page content *#
#Html.DisplayFor(x => x.Posts)
<div id="more"></div>
#Ajax.ActionLink("Read More", "More", "Blog", new AjaxOptions {
InsertionMode = InsertionMode.InsertBefore,
UpdateTargetId = "more"
})
#* Other page content *#
~/Views/Blog/More.cshtml
#model PostsViewModel
#Html.DisplayFor(x => x.Posts)
~/Views/Blog/DisplayTemplates/PostViewModel.cshtml
#model PostViewModel
#* Display post itself *#

Related

When rendering my partial view it is not set it an instance of an object

I am attempting to use partial views for the first time and I need some help. I am posting a string from Javascript to my ASP controller so that I can query my database using that string. Like so:
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
error: function (e) {
console.log(e)
console.log("error")
}
});
}
Controller
[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
string county = userCounty.Substring(0, userCounty.IndexOf(" "));
var query = from SOP in _context.SalesOffice_Plant
where SOP.County == county
select new SalesOffice_Plant
{
Employee = SOP.Employee
};
return PartialView(query.ToList());
}
[HttpGet]
public ActionResult Index()
{
ViewData["Title"] = "Contact Us";
ViewBag.Current = "Contact";
return View();
}
When I set break points - I can see that the string is passed correctly and my LINQ query works just fine. My problem occurs when I want to render a table of the employees in my Index page. The JavaScript returns a value to the controller after the page loads. This means I needed a way to "refresh the page". I was told to use a partial view to solve this problem and this is what I came up with.
Index.cshtml
#model IEnumerable<Project.Models.SalesOffice_Plant>
//A bunch of Html
#await Html.PartialAsync("_IndexPartial")
//More Html
_IndexPartial.cshtml
#model IEnumerable<Project.Models.SalesOffice_Plant>
<table class="table">
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Employee)
</td>
</tr>
}
</tbody>
Ideally, I would like a table of Employees to be generated and displayed in the Index.cshtml. However, when I load the page I get and error telling me that my #await Html.PartialAsync("_IndexPartial") 'is not set to an instance of an object.
Any pointers in the right direction would be very helpful.
When you use ajax,it would not reload your page after backend code finishing,so you need to use .html() method to render the backend result to html.
Here is a whole working demo:
Model:
public class SalesOffice_Plant
{
public int Id { get; set; }
public string County { get; set; }
public string Employee { get; set; }
}
View(Index.cshtml):
<button type="button" onclick="findEmployees('a ')">Find</button>
<div id="employee">
</div>
#section Scripts
{
<script>
function findEmployees(userCounty) {
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
error: function (e) {
console.log(e)
console.log("error")
},
success: function (res) {
$("#employee").html(res); //add this...
}
});
}
</script>
}
Partial View(_IndexPartial.cshtml):
#model IEnumerable<SalesOffice_Plant>
<table class="table">
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Employee)
</td>
</tr>
}
</tbody>
</table>
Controller:
[HttpPost]
public ActionResult Index([FromBody] string userCounty)
{
string county = userCounty.Substring(0, userCounty.IndexOf(" "));
var query = from SOP in _context.SalesOffice_Plant
where SOP.County == county
select new SalesOffice_Plant
{
Employee = SOP.Employee
};
return PartialView("_IndexPartial", query.ToList()); //must specify the partial view name
//otherwise it will match the action name as partial view name
}
[HttpGet]
public ActionResult Index()
{
ViewData["Title"] = "Contact Us";
ViewBag.Current = "Contact";
return View();
}
Result:

list of object to single selected object on submit form button razor mvc c#

i have razor view with List. but on submit button i want to send selected Employee[0] or any other index Employee[1] to respected controller.
let suppose.
#model List<Employee>
#for(int i=0;i<Model.Count;i++)
{
#using (Html.BeginForm("A", "B", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#html.TextBoxFor(x=>x[i].Name);
<input id="abc" type=submit>
}
}
public Acontroller()
{
public ActionResult B(Employee employee)
{
employee.Name.....
}
}

Validation fires but doesn't show message on failure. What am I missing? MVC 5 Razor

I can't seem to get the Validation error messages to show under the input model fields on the View.
The [Required] tag above Description input makes the ModelState Invalid, but doesn't stop the submission. I have to catch it with checking the Model State. Am I missing some .js files? I dont' have any examples to doublecheck this.
Here is my model (notice I have only one [Required] for now):
public partial class Requests
{
public int RequestID { get; set; }
public string NickName { get; set; }
public Nullable<double> Lat { get; set; }
public Nullable<double> Lng { get; set; }
public string ZipCode { get; set; }
[Required(ErrorMessage = "Description of what you need is missing.")]
public string Description { get; set; }
public System.DateTime DateCreated { get; set; }
}
Here is my View where the Description input needs input.
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { #class = "form-control", #rows = "20", #cols = "200" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
Here is my controller ActionResult (skinnied down)
if (ModelState.IsValid)
{
//THIS ALL WORKS IF Description HAS INPUT
}
else
{
TempData["Saved"] = "Nothing saved yet. Look for reason.";
return RedirectToAction("StoreRequests", new { lat = requests.Lat, lng = requests.Lng });
}
On ModelState failure the user is directed to the correct View and TempData shows that nothing was saved. However, there is no error message on the View below the offending input, no ValidationSummary at the top of the view, and submission is not stopped on input mistake.
#if(TempData["Saved"] != null)
{
<span style="color: red;">#TempData["Saved"].ToString()</span>
}
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
In order to get client side validation (and therefore prevent the form being submitted if its invalid), you need to include the following scripts in you view (or layout).
jquery-{version}.js
jquery.validate.js
jquer.validate.unobtrusive.js
If you have the default bundles set up by VS when you create a new project, you can simply add the following to the view
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
In addition, you should not be redirecting if ModelState is invalid, but rather returning the current view, which will display any validation errors even if the user has disabled javascript. By redirecting, your lose current ModelState so no validation errors will be displayed in the view your redirecting to, not to mention that any data the user previously filled (except the 2 parameters your passing) will be lost.
public ActionResult Edit (Requests model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// save you data and redirect
}
Include the following necessary scripts directly in your .cshtml file.
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

How to use Jquery/Ajax with asp.net MVC 4 with partial view and action with model

I am new to both asp.net MVC and JQuery so be gentle.
I am trying to use a HTTP Post to update my contact form, used to send an email, using AJAX. I have seen lots of posts but what I want seems specific and I cant seem to find anything relevant.
The down low: I have a layout page which has the header, renders the body and has my footer in. My footer contains the form I want to submit. I want to submit this form without refreshing the whole page. The layout page:
<div id="footer">
#{Html.RenderAction("Footer", "Basic");}
</div>
<p id="p"></p>
I have a model for this form to send an email.
namespace SimpleMemberShip.Models
{
public class EmailModel
{
[Required, Display(Name = "Your name")]
public string FromName { get; set; }
[Required, Display(Name = "Your email"), EmailAddress]
[StringLength(100, ErrorMessage = "The email address entered is not valid")]
public string FromEmail { get; set; }
[Required]
public string Message { get; set; }
}
The footer:
<h2> footer yo !</h2>
#Html.ValidationSummary()
<fieldset>
<legend>Contact Me!</legend>
<ol>
<li>
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail)
</li>
<li>
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName)
</li>
<li>
#Html.LabelFor(m => m.Message)
#Html.TextBoxFor(m => m.Message)
</li>
</ol>
<button id="submit"> Submit </button>
</fieldset>
controller:
[ChildActionOnly]
public ActionResult Footer()
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
[HttpPost]
public ActionResult Footer(EmailModel model)
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
I want to use the model validation and everything to be the same or similar as if the form was posted normally through the server.
Edit:
My new code, which works great! but it only works once, when the button is clicked again nothing happens. Anyone know why?
<script type="text/javascript">
$("#submit").click(function () {
$("#footer").html();
var url = '#Url.Action("Footer", "Basic")';
$.post(url, { FromName: $("[name=FromName]").val(), FromEmail: $(" [name=FromEmail]").val(), Message: $("[name=Message]").val() }, function (data) {
$("#footer").html(data);
});
var name = $("[name=FromName]").val();
$("#p").text(name);
});
</script>
new Edit:
did some research and using
$("#submit").live("click",function () {
instead of
$("#submit").click(function () {
seemed to do the trick.
<script type="text/javascript">
$("#submit").live("click",function () {
$('.validation-summary-errors').remove();
var url = '#Url.Action("Footer", "Basic")';
$.post(url, { FromName: $("[name=FromName]").val(), FromEmail: $("[name=FromEmail]").val(), Message: $("[name=Message]").val() }, function (data) {
$("#footer").html(data);
});
});
</script>
ended up with this but will try the "serialize()" option next time.
controller was changed to this without the [ChildActionOnly] and works perfect now
[HttpPost]
public ActionResult Footer(EmailModel model)
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
Thank you everyone that helped!
Change the [ChildActionOnly] to [HttpGet] in the controller
You can pass model data to controller by doing the following steps
1. Get the input values on click of submit and sent to the Footer action in controller
$("#submit").click(function () {
var FromEmailValue = $('#FromEmail').val();
var FromNameValue = $('#FromName').val();
var MessageValue = $('#Message').val();
var url = '#Url.Action("Footer", "Basic")';
$.ajax({
url: urlmodel,
data: { FromName: FromNameValue, FromEmail: FromEmailValue, Message: MessageValue},
cache: false,
type: "POST",
success: function (data) {
do something here
}
error: function (reponse) {
do something here
}
});
});
In the controller
``
[HttpGet]
public ActionResult Footer()
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
[HttpPost]
public ActionResult Footer(string FromName = "", string FromEmail = "", string Message = "")
{
//for ajax request
if (Request.IsAjaxRequest())
{
do your stuff
}
}

Ajax.Begin Form client side validation in Partial View MVC5.2

Index.cshtml:
<div class="search-ctn">
#{ Html.RenderAction(MVC.Home.Search()); }
</div>
Search.cshtml:
#model ViewModels.SearchVM
#using (Ajax.BeginForm(MVC.Home.Search(), new AjaxOptions { UpdateTargetId = "idx-list-ctn", InsertionMode = InsertionMode.Replace }, new { #id = "sch-frm" }))
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(m => m.Service)
#Html.ValidationMessageFor(m => m.Service)
}
MVC.Home.Search Action:
[HttpPost, ValidateAntiForgeryToken]
public virtual PartialViewResult Search(SearchVM partnerSearch)
{
// Search made here
}
ViewModel:
public class SearchVM
{
[Required]
public string Service { get; set; }
}
Libraries:
jquery-2.1.3.js
jquery.unobtrusive-ajax.js (v3.2.3)
jquery.validate.js (v1.13.1)
jquery.validate.unobtrusive.js (v3.2.3)
In an old project using jquery-1.10.2.js I was activating the form's validation like this:
$.validator.unobtrusive.addValidation("#sch-frm");
and it was working just fine, but now it's submiting the form ignoring the validation.

Categories

Resources