I code web MVC4 by VS2012. I use Ajax to paging in list page, when ajax working is double result. Below is my code:
This is View:
<div id="result">
<% using (Ajax.BeginForm("Paging","pa",new AjaxOptions{UpdateTargetId="result"})){ %>
<table>...<table>
<div class="Paging"><%= ViewBag.PhanTrang %></div>
<%} %></div>
<script>
$(function () {
$('.a_pt').click(function () {
var _val = $(this).data("id");
$.ajax({
url: this.action,
type: this.method,
data: { id: _val },
success: function (result) {
$('#result').html(result);
}
});
return false;
});
});
</script>
This is Controller:
public ActionResult Paging(string id)
{
demoMVC4Entities db = new demoMVC4Entities();
var _listProvince = db.T_Provinces;
ViewBag.ddl_Province = new SelectList(_listProvince, "Province_ID", "Province_Name");
var _listStudent = db.T_Student.OrderBy(n => n.MA).Skip((_pageIndex - 1) * pageSize).Take(pageSize);
return View(_listStudent);
}
And this is first result:
<body>
<p>...</p>
<div id="result">
<form action=.............></form>
</div>
And this í second result:
<body>
<p>...</p>
<div id="result">
<form action=.............>
___<body>
___<p>...</p>
___<div id="result">
___<form action=.............></form>
___</div>
</form>
</div>
Plese help me.! Thanks.!
I think you are updating the target id (#result) twice. Either remove the success function in the javascript or remove the UpdateTargetId in the Ajax Options.
hth
O
Create a Partial View named: WhateverList.cshtml
Put this is in a Partial View:
<% using (Ajax.BeginForm("Paging","pa",new AjaxOptions{UpdateTargetId="result"})){ %>
<table>...<table>
<div class="Paging"><%= ViewBag.PhanTrang %></div>
<%} %></div>
Keep this in the current view you have:
<div id="result"></div>
Then in Controller do this:
public ActionResult WhateverList(string id)
{
demoMVC4Entities db = new demoMVC4Entities();
var _listProvince = db.T_Provinces;
ViewBag.ddl_Province = new SelectList(_listProvince, "Province_ID", "Province_Name");
var _listStudent = db.T_Student.OrderBy(n => n.MA).Skip((_pageIndex - 1) * pageSize).Take(pageSize);
return PartialView(_listStudent);
}
And you only need either the jQUery Ajax OR the Ajax.BeginForm not both:
I suggest you use jQuery in this Case:
<script>
$(function () {
$('.a_pt').click(function () {
var _val = $(this).data("id");
$.ajax({
url: this.action,
type: this.method,
data: { id: _val },
success: function (result) {
$('#result').html(result);
}
});
return false;
});
});
</script>
And remove the Ajax.BeginForm from your PartialView:
So Partial View is only:
#model SelectList
<table>...<table>
<div class="Paging"><%= ViewBag.PhanTrang %></div>
When you return View(), it will render the _Layout.cshtml of the Page , and return the <html>, <body> tags. But return PartialView() only returns the HTML content of the Partial View without Layout.cshtml
Related
I have a problem with my controller - it doesn't return a view. I am sending some data to the same controller, creating a new object with this data and I would like to send this object to the Create view but for some kind of reason I am staying on the same page.
View name: Create.cshtml
Controller name: ReservationController
Here is my controller action:
public IActionResult Create(int selectedTime, string selectedDate, int selectedRoomId)
{
TimeSpan time = TimeSpan.Parse($"{selectedTime}:00:00");
DateTime date = DateTime.ParseExact(selectedDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
DateTime combine = date + time;
Reservation reservation = new Reservation();
reservation.RoomId = selectedRoomId;
reservation.ReservationTime = combine;
return View(reservation);
}
And my view:
#model Escape.Models.Reservation
#{
ViewBag.Title = "title";
}
<h2>My create reservation view</h2>
This is the original view I am coming from:
#using Escape.Controllers
#model Escape.Models.Room
#{
ViewData["Title"] = "Details";
}
<h4 class="title">Booking for room: #Model.Name</h4>
<div>
<p>#Model.Description</p>
<a class="btn btn-link" asp-action="Index">Back to all rooms</a>
<hr />
</div>
<div>
<input id="datepicker" type="text" name="datepicker"
onchange="onDateChange(#Model.Id)" />
</div>
<div>
<div id="displayTimes"></div>
<a id="btn-create" class="btn btn-sm"></a>
</div>
#section Scripts {
<script>
var dateToday = new Date();
$(function () {
$("#datepicker").datepicker({
minDate: dateToday
});
});
</script>
}
Ajax function on my btn-create:
function onButtonClick(val, date, room) {
var btnBack = document.getElementById("btn-create");
btnBack.innerHTML = "Create reservation";
$(btnBack).addClass('btn-outline-primary');
btnBack.addEventListener("click",
function () {
$.ajax({
type: "GET",
data: { selectedTime: val, selectedDate: date, selectedRoomId: room },
url: "/Reservation/Create",
contentType: "application/json",
dataType: "json"
});
});
}
If the link <a id="btn-create" class="btn btn-sm"></a> is supposed to make a call to the Create method of the ReservationController, then it is incomplete, and this is what you would need to change it to:
<a asp-controller="Reservation"
asp-action="Create"
id="btn-create" class="btn btn-sm">Create</a>
Update:
Your click handler does seem to send a request to the Controller, but nothing happens after that request, and the response (which contains the HTML from the View) is discarded.
Since you want to show the HTML, maybe you shouldn't even be using AJAX, and use my original answer above instead.
If for some reason you need the AJAX, then you need to create a success handler that displays the HTML:
btnBack.addEventListener("click",
function () {
$.ajax({
type: "GET",
data: { selectedTime: val, selectedDate: date, selectedRoomId: room },
url: "/Reservation/Create",
contentType: "application/json",
dataType: "json",
success: function (data) {
// ... put processing here
}
});
}
);
I want to show PDF without Download Option. After many search of Google I get some answer but I'm facing a problem in this.
PDF is open in partial View, but there have also Download Option. Is there another option to open Pdf without Download option?
#model Bizzop.Models.MyAccountModel
#{
Layout = null;
}
<html>
<head>
<title>INDEX</title>
</head>
<body>
<div id="divPartialView">
</div>
<div class="container">
#if (Model.MyAccountList.Count > 0)
{
foreach (var items in Model.MyAccountList)
{
<div class="video-row">
<a href="#" target="_blank" onclick="myPdf(this)"
id="#items.PdfName">
<div class="row">
#if (items.PdfName == "" || items.PdfName == null)
{
<img src="ImageName"/>
}
else
{
<img src="ImageName"/>
}
</div>
</a>
</div>
}
}
</div>
////// This is Ajax code where we pass File name when click the user in anchor
tag
<script>
function myPdf(e) {
debugger
var filen = e.id;
$.ajax({
url: "/MyAccount/MyPdfResult",
data: { pdfname: filen },
cache: false,
type: "POST",
dataType: "html",
type: "post",
success: function (data) {
SetData(data);
},
error: function (data) {
}
});
function SetData(data) {
$("#divPartialView").html(data); // HTML DOM replace
}
}
</script>
/////////// In Controller
public ActionResult MyPdfResult(string pdfname = null)
{
string embed = "<object data=\"{0}\" type=\"application/pdf\"
width=\"500px\" height=\"300px\">";
embed += "</object>";
TempData["Embed"] = string.Format(embed,
VirtualPathUtility.ToAbsolute("~/Content/TutorialImage/TutorialPdf/"+
pdfname));
return PartialView("_Viewpdf", TempData["Embed"]);
}
///// where i am create a Partial View
<div class="ancor">
#Html.Raw(TempData["Embed"])
</div>
i just tried it on my side and it worked for me. You need to make sure that your app is allowed to access the pdf file.
This is my code:
The controller:
[HttpPost]
[AllowAnonymous]
public ActionResult MyPdfResult(string pdfname = null)
{
string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
embed += "If you are unable to view file, you can download from here";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
TempData["Embed"] = string.Format(embed, VirtualPathUtility.ToAbsolute("~/Files/pdf.pdf"));
return PartialView("_Viewpdf", TempData["Embed"]);
}
The partial view:
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
#using (Html.BeginForm("MyPdfResult", "Home", FormMethod.Post))
{
View PDF
<hr />
#Html.Raw(TempData["Embed"])
}
The Index:
<div>
#Html.Partial("_Viewpdf");
</div>
I'm using Recaptcha in my MVC4 web app. It was working correctly when it was embedded in the form but when I moved the #Html.Raw(Html.GenerateCaptchaHelper()) to partial view and trying to call this partial view via ajax request, it doesn't work!
Extension code :
public static string GenerateCaptchaHelper(this HtmlHelper helper)
{
var captchaControl = new Recaptcha.RecaptchaControl
{
ID = "recaptcha",
Theme = "clean",
PublicKey = ************,
PrivateKey = **********************,
Language = "En"
};
var htmlWriter = new HtmlTextWriter(new StringWriter());
captchaControl.RenderControl(htmlWriter);
return htmlWriter.InnerWriter.ToString();
}
my partial view is has the code like :
<p>#Html.Raw(Html.GenerateCaptchaHelper())</p>
and inside my controller
public PartialViewResult Captcha()
{
return PartialView();
}
and inside my main view:
#using (Html.BeginForm("Login", "Account", new { returnUrl = ViewData["ReturnUrl"] }, FormMethod.Post,null))
{
#Html.AntiForgeryToken()
<form role="form">
<div class="form-group">
<label>#Html.LabelFor(m => m.Email)</label><br />
#Html.TextBoxFor(m => m.Email, null, new { #class = "form-control", autocomplete = "off" })
</div>
<div class="form-group">
<label>#Html.LabelFor(m => m.Password)</label><br />
#Html.PasswordFor(m => m.Password, new { #class = "form-control", autocomplete = "off" })
</div>
<div id="captchaView" class="form-group">
</div>
<button type="submit">Login</button>
</div>
</div>
</form>
}
and the javascript is :
$.ajax({
url: '/Account/Captcha',
type: 'GET',
success: function(data) {
$('#captchaView').html(data);
}
});
Could you please help me to figure out why?
I am using asp.net MVC 5 to do a simple single file upload using the HTML element.I make an AJAX post request.The form has other fileds in addition to the file element.I tried diffrent methods available on the internet ,but nothing seems to be working.Is this really possible using the element?Using a jQuery plugin is my last option.I like to make things simple in my application
my HTML
#using (Html.BeginForm("Edit", "Person", FormMethod.Post, new { id = "form-person-edit-modal", enctype = "multipart/form-data" }))
{
<div class="row">
<div class="row">
<div class="small-4 columns">
#Html.GenericInputFor(m => m.Name, Helpers.HtmlInputType.Text, new { id = "input-name" })
</div>
<div class="small-4 columns">
#Html.GenericInputFor(m => m.Description, Helpers.HtmlInputType.TextArea, new { id = "input-description" })
</div>
<div class="small-4 columns">
<label>Choose File</label>
<input type="file" name="attachment" id="attachment" />
</div>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<input type="submit" id="image-submit" value="Save"/>
</div>
</div>
}
-- C# ViewModel
public class Person
{
Public string Name{get;set;}
Public string Description{get;set;}
public HttpPostedFileBase Attachment { get; set; }
}
-- Jquery Ajax Post:
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
dataType: 'json',
success: function (data, textStatus, jqXHR) {
if (data.Success) {
success(data, textStatus, jqXHR);
} else {
if (error) {
error();
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (error)
error();
}
});
-- Javacsript where I try to get the file content,before passing that data to the above method
function getData(){
return {
Name:$('#input-name').val(),
Description:$('#input-description').val(),
Attachment:$('#form-ticket-edit-modal').get(0).files[0]
};
}
But the Attachment on the controller is null.I tried this as below,but doesnt seem to be working
[HttpPost]
public ActionResult Edit(ViewPerson person,HttpPostedFileBase attachment)
{
}
Is this still possible,or should I use a jQuery plugin(If so,which one do you recommend?)
I have used your code to show how to append image file,Please use Formdata() method to append your data and File and send through ajax.
Try Changing as per your requirement.
$("#SubmitButtonID").on("click",function(){
var mydata=new Formdata();
mydata.append("Name",$("#name").val());
mydata.append("Image",Image.files[0]);
alert(mydata);
$.ajax({
url: "#url.Action("ActionMethodName","ControllerName")",
type: 'POST',
contentType:false,
processData;false,
data: mydata,
dataType: 'json',
success: function (data, textStatus, jqXHR) {
if (data.Success) {
success(data, textStatus, jqXHR);
} else {
if (error) {
error();
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (error)
error();
}
});
});
<input type="file" id="Image" name="file">
<input type="button" id="SubmitButtonID" value="submit"/>
I have this controller and view:
public ActionResult DynamicView()
{
return View();
}
_
#model ChatProj.Models.GroupNumber
#{
ViewBag.Title = "DynamicView";
}
<h2>DynamicView</h2>
<fieldset>
<legend>Create a room</legend>
<div class="editor-label">
#Html.LabelFor(model => model.GroupId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.GroupId)
#Html.ValidationMessageFor(model => model.GroupId)
</div>
<input type="submit" value="DynamicView" />
</fieldset>
This is what it looks like on the page.
That's fine and dandy, but I would like to pass that number to a controller, which then passes it to a view. I would like to pass it to this view:
#using PagedList.Mvc;
#using ChatProj.App_Code;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Grupprum 1";
}
<h2>Grupprum 1</h2>
<style>
ul {list-style-type:circle;}
</style>
<div class="container">
<div class="nano chat">
<div class="content">
<ul id="discussion">
</ul>
</div>
</div>
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" disabled="disabled" />
<input type="hidden" id="displayname" />
</div>
#section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-1.1.3.js"></script>
<script src="~/Scripts/jquery.nanoscroller.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
$(".nano").nanoScroller();
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
$(document).ready(function () {
$("#sendmessage").removeAttr("disabled");
$('#message').keypress(function (e) {
if (e.keyCode == 13)
$('#sendmessage').click();
});
});
// Get the user name and store it to prepend to messages.
// Set initial focus to message input box.
$('#message').focus();
$.connection.hub.qs = { "room": "Grupprum 1" };
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
Specifically I would want it at $.connection.hub.qs = { "room": "Grupprum 1" }; to replace the 1.
So I've created these controllers which are faulty and incomplete:
[HttpPost]
public ActionResult DynamicView(int? roomNumber)
{
return View(GroupRoom(roomNumber));
}
public ActionResult GroupRoom(int roomNumber)
{
return View();
}
Does anyone know how I should change my controllers and views so that I'm able to insert a number in my DynamicGroup view, and get a view back based on the inserted number and the lastly mentioned view?
You could pass the number from the model to the new action just how #Matt Bodily did. But if you want to use a different model on your new view, you can use the below code instead:
public ActionResult GroupRoom(int roomNumber)
{
ViewBag.RoomNumber = roomNumber;
return View();
}
This way, you can use a different model for this page, if you want to. To display this ViewBag on the page, use this code anywhere you want:
#ViewBag.RoomNumber
I hope that helps you out.
How you have it set up the Model.GroupID will be set on the first view so change your controller like this
[HttpPost]
public ActionResult DynamicView(GroupNumber model)
{
//model.GroupId here will be what was selected on the first view
return RedirectToAction("GroupRoom", "Controller", new { GroupId = model.GroupId });
}
public ActionResult GroupRoom(int GroupId)
{
var model = //build your model based on the selected GroupId
return View(model);
}