Partial view render on button click - asp.net

I have Index view:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width" />
<title>MsmqTest</title>
</head>
<body>
<div>
<input type="submit" id="btnBuy" value="Buy" onclick="location.href='#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })'" />
<input type="submit" id="btnSell" value="Sell" onclick="location.href='#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })'" />
</div>
<div id="msmqpartial">
#{Html.RenderPartial("Partial1", Model); }
</div>
</body>
</html>
and partial:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<p>
Items to buy
#foreach (var item in Model.ItemsToBuy)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
<p>
<a>Items Selled</a>
#foreach (var item in Model.ItemsSelled)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
And controller:
public class MsmqTestController : Controller
{
public MsmqData data = new MsmqData();
public ActionResult Index()
{
return View(data);
}
public ActionResult BuyItem()
{
PushIntoQueue();
ViewBag.DataBuyCount = data.ItemsToBuy.Count;
return PartialView("Partial1",data);
}
}
How to do that when i Click one of button just partial view render, now controller wants to move me to BuyItem view ;/

The first thing to do is to reference jQuery. Right now you have referenced only jquery.unobtrusive-ajax.min.js but this script has dependency on jQuery, so don't forget to include as well before it:
<script src="#Url.Content("~/Scripts/jquery.jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Now to your question: you should use submit buttons with an HTML form. In your example you don't have a form so it would be semantically more correct to use a normal button:
<input type="button" value="Buy" data-url="#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })" />
<input type="button" value="Sell" data-url="#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })" />
and then in a separate javascript file AJAXify those buttons by subscribing to the .click() event:
$(function() {
$(':button').click(function() {
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
success: function(result) {
$('#msmqpartial').html(result);
}
});
return false;
});
});
or if you want to rely on the Microsoft unobtrusive framework you could use AJAX actionlinks:
#Ajax.ActionLink("Buy", "BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
#Ajax.ActionLink("Sell", "SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
and if you want buttons instead of anchors you could use AJAX forms:
#using (Ajax.BeginForm("BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Buy</button>
}
#using (Ajax.BeginForm("SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Sell</button>
}
From what I can see you have already included the jquery.unobtrusive-ajax.min.js script to your page and this should work.

Maybe not the solution you were looking for but, I would forget about partials and use Javascript to call the server to get the data required and then return the data to the client as JSON and use it to render the results to the page asynchronously.
The JavaScript function;
var MyName = (function () {
//PRIVATE FUNCTIONS
var renderHtml = function(data){
$.map(data, function (item) {
$("<td>" + item.whateveritisyoureturn + "</td>").appendTo("#msmqpartial");
});
};
//PUBLIC FUNCTIONS
var getData = function(val){
// call the server method to get some results.
$.ajax({ type: "POST",
url: "/mycontroller/myjsonaction",
dataType: "json",
data: { prop: val },
success: function (data) {
renderHtml();
},
error: function () {
},
complete: function () {
}
});
};
//EXPOSED PROPERTIES AND FUNCTIONS
return {
GetData : getData
};
})();
And on the Server....
public JsonResult myjsonaction(string prop)
{
var JsonResult;
// do whatever you need to do
return Json(JsonResult);
}
hope this helps....

Related

Fluent Validation: Changing control style on error

I'm using Fluent Validation in my ASP.NET MVC application. I need to change the CSS class of the control when there's an error. Please see my code below.
using FluentValidation;
using Hrms.Framework.Common;
using Hrms.Web.Models;
namespace Hrms.Web.InputValidators
{
public class AnnouncementValidator : AbstractValidator<AnnouncementModel>
{
public AnnouncementValidator()
{
RuleFor(a => a.Title).NotEmpty().WithMessage("Announcement Title is required");
RuleFor(a => a.Title).MaximumLength(50).WithMessage(string.Format("Announcement Title should be 50 characters or less", 50));
}
}
}
Here is the code I have in the view (HTML)
#model Hrms.Web.Models.AnnouncementModel
#{
Layout = "~/Views/Shared/_Application.cshtml";
}
#using (Ajax.BeginForm("Save", "Announcement", new AjaxOptions
{
HttpMethod = "POST",
OnFailure = "saveFailed",
OnSuccess = "saveSucc",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "result"
}))
{
#Html.AntiForgeryToken()
<div id="result"></div>
<label>#Resources.Organization.Announcement.Title</label>
#Html.TextBoxFor(m => m.Title, new { maxlength = #GlobalConstants.AnnouncementTitleMaxLength })
#Html.ValidationMessageFor(model => model.Title, null, new { #class = "errVal" })
<input type="submit" value="Save">
}
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#SendingDate").datepicker();
});
function saveSucc(m) {
$("#Title").val("");
$("#Body").val("");
$("#SendingDate").val("");
}
function saveFailed() {
alert("saveFailed");
}
</script>
}
Any help is highly appreciated
When I tried to edit this post, it showed an error saying that I cannot edit this post because it is mostly code, it asked me to add more details. And because there are no more details in my mind to add, I decided to add this text. I'm sorry...

how can I get the selected value of checkboxlist and passed that value from view to controller using jquery

view:
#using (Ajax.BeginForm("Searchbyquality", "Health", new AjaxOptions { HttpMethod = "POST" }))
{
foreach (var item in Model.QualityModel)
{
<li><input type="checkbox" name="qualitycheck"/><span>item.qualityName</span></li>
}
}
Controller:
public ActionResult Searchbyquality(string[] qualitycheck )
{
//code of searching
}
I want to pass multiple selected value to the controller
Your View Code Should be :
#using (Ajax.BeginForm("Searchbyquality", "Health", new AjaxOptions { HttpMethod = "POST" }))
{
foreach (var item in Model.QualityModel)
{
<div class="checkbox">
<label>
<input type="checkbox"
name="qualitycheck"
value="#item.qualityName" /> #item.qualityName
</label>
</div>
}
#*<div class="form-group text-center">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>*#
}
For without Submit button you have to add jQuery Code to call controller action :
$( document ).ready(function() {
$(":checkbox").change(function() {
if(this.checked) {
var qualitycheck_data = { 'qualitycheck': [] };
$('input:checked').each(function ()
{
if(this.name == 'qualitycheck') qualitycheck_data['qualitycheck'].push($(this).val());
});
var path = "/Health/Searchbyquality";
$.ajax({
url: path, type: "POST", cache: "false",
dataType: "json", contentType: "application/json; charset=utf-8",
data: JSON.stringify(qualitycheck_data),
traditional: true,
converters: {'text json': true}
}).success(function (responseText) {
//Success result
window.location.assign(responseText);
}).error(function (responseText){
swal("Error!", "Test 1", "error");
});
//swal("Error!", "Test 2", "error");
}
});
});
And your Controller Action :
[HttpPost]
public ActionResult Searchbyquality(string[] qualitycheck )
{
//code of searching
return View("");
}
cheers !!

ASP.NET Upload file return its content

I'm trying to upload a file then retrieve its content as JSon
My controller :
controller.cs
[HttpPost]
public JsonResult Upload(HttpPostedFileBase file)
{
List<string> list = doStuff(file);
return Json(list);
}
My view :
view.cshtml
#using (Html.BeginForm("Upload", "Files", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="file" name="file" />
<input type="submit" name="Upload" value="Upload" />
}
When I upload a file it propose me to download a JSON file, but what I want is to set a javascript variable with this JSON so I can use it directly on my webpage.
I believe that the best solution is to use an ajax form.
See the example below:
Controller:
[HttpPost]
public JsonResult Upload(HttpPostedFileBase file)
{
return Json(new { ReturnMessage = "Success!!!!!" + file.FileName});
}
View:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { #id="formUploadFile", #onsubmit = "return SubmitFormWithFile();" }))
{
#Html.TextBox("file", null, new { #type = "file", #id = "file" })
<button type="submit">Send</button>
}
Javascript:
function SubmitFormWithFile() {
var form = $("#formUploadFile");
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: new FormData(form[0]),
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
alert("Before Send");
},
success: function (dataResult) {
//set its variable here...
//the dataResult is returned json...
alert(dataResult.ReturnMessage);
},
error: function () {
alert("Error");
}
});
return false;
}

pass parameter from View to Controller in asp mvc

I am trying to pass parameter from view to controller,
This is my View:
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#foreach (var pricedetails in ViewBag.PriceTotal)
{
<div style="text-align:center; clear:both ">
<h5 class="product-title">#pricedetails.Title</h5>
</div>
<div class="product-desciption" style="height:40px">#pricedetails.Descriptions</div>
<p class="product-desciption product-old-price"> #pricedetails.PricePoints</p>
<div class="product-meta">
<ul class="product-price-list">
<li>
<span class="product-price">#pricedetails.PricePoints</span>
</li>
<li>
<span class="product-save">Get This Free</span>
</li>
</ul>
<ul class="product-actions-list">
<input type="submit" name='giftid' value="Get Gift"
onclick="location.href='#Url.Action("Index", new { id = pricedetails.PriceId })'" />
</ul>
</div>
}
}
my action method:
On submit it reaches the Action Method, but I am not able to get the PriceId for each Price
[HttpPost]
public ActionResult Index(int id=0) // here PriceId is not passed on submit
{
List<Price_T> priceimg = (from x in dbpoints.Price_T
select x).Take(3).ToList(); ;
ViewBag.PriceTotal = priceimg;
var allpoint = singletotal.AsEnumerable().Sum(a => a.Points);
var price = from x in dbpoints.Price_T
where x.PriceId == id
select x.PricePoints;
int pricepoint = price.FirstOrDefault();
if (allpoint < pricepoint)
{
return Content("<script language='javascript' type='text/javascript'>alert('You are not elgible');</script>");
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('You are elgible');</script>");
}
return View("Index");
}
Url Routing:
routes.MapRoute(
name: "homeas",
url: "Index/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
May I know what wrong I am doing ?
Please use the following in your cshtml page
#foreach (var item in Model)
{
#Html.ActionLink(item.PriceDetails, "GetGift", new { priceID = item.priceID }, new { #class = "lnkGetGift" })
}
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a.lnkGetGift").on("click", function (event) {
event.preventDefault();
$.get($(this).attr("href"), function (isEligible) {
if (isEligible) {
alert('eligible messsage');
}
else
{
alert('not eligible messsage');
}
})
});
});
</script>
and in controller
[HttpGet]
public JsonResult GetGift(int priceID)
{
List<Price_T> priceimg = (from x in dbpoints.Price_T
select x).Take(3).ToList(); ;
ViewBag.PriceTotal = priceimg;
var allpoint = singletotal.AsEnumerable().Sum(a => a.Points);
var price = from x in dbpoints.Price_T
where x.PriceId == id
select x.PricePoints;
int pricepoint = price.FirstOrDefault();
if (allpoint < pricepoint)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
Please change your parameters according to the method param and price entity
Hope this helps.
I suggest you get rid of the Html.BeginForm(). Just leave the for...loop and define your "Get Gift" button like this:
<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(#(pricedetails.PriceId))'" />
Then, at the bottom of the view file where the Get Gift button is located, define some JavaScript:
<script type="text/javascript">
function getGift(priceId) {
$.ajax({
type: 'GET',
url: '#Url.Action("Index", "Home")',
data: { priceId: priceId },
contentType : "json",
success:function(data){
// Do whatever in the success.
},
error:function(){
// Do whatever in the error.
}
});
</script>
By using an ajax call to get the gift data, you don't have to submit anything. This makes things a lot easier in your case. Pressing the Get Gift button simply makes an ajax call.
I don't have time to try this out myself, but hopefully the above example should get you up and running.
EDIT:
I've managed to sneak in some time to come up with an example.
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var items = new List<int>();
items.Add(1);
items.Add(2);
items.Add(3);
return View(items);
}
public ActionResult GetGift(int priceId)
{
return RedirectToAction("Index"); // You'll be returning something else.
}
}
View
#model List<int>
#foreach (var price in Model)
{
<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(#(price))" />
}
<script type="text/javascript">
function getGift(priceId) {
$.ajax({
type: 'GET',
url: '#Url.Action("GetGift", "Home")',
data: { priceId: priceId },
contentType: "json",
success: function(data) {
// Do whatever in the success.
},
error: function() {
// Do whatever in the error.
}
});
}
</script>
Hope this helps you.
I think you should correct here
<input type="button" name='giftid' value="Get Gift"
onclick="location.href='#Url.Action("Index", new { id = pricedetails.PriceId })'" />

KnockoutJS, get data from spring mvc controller and bind it to the view

im trying knockout doing a little test and i have not been able to do this very basic thing with knockout.. i want to return a list from my controller then take that list with my knockout viewmodel and finally bind it to a dropdown in my view.
i have this controller:
#RequestMapping(value="/getUsers", method = RequestMethod.GET)
public List<User> returnUsers(#ModelAttribute User user) {
User user1=new User(), user2, user3 ;
List<User>users=new ArrayList<User>();
user1.setLastName("adsfa");
user1.setName("adfds");
user1.setAge(26);
user2=new User();
user2.setLastName("testLastName2");
user2.setName("testName2");
user2.setAge(45);
user3=new User();
user3.setLastName("testLastName2");
user3.setName("testName3");
user3.setAge(33);
users.add(user1);
users.add(user2);
users.add(user3);
return users;
}
this is my knockout viewmodel:
function viewModel() {
this.name = ko.observable("bob");
this.lastName = ko.observable("smith");
this.age = ko.observable(26);
this.validationMessage = ko.observable();
this.users = ko.observableArray([]);
this.loadUsers(); //with this function call i want to initialize users with my controller data.
}
//this funcion should get the data from my controller
viewModel.prototype.loadUsers = function() {
var tmp = this.users();
$.get("/vacation_booking/getUsers", function (data) {
tmp(ko.toJS(data));
log.info("Usuarios:" + data);
});
}
/*
this.Age = ko.dependentObservable({
read: this.age,
write: function (value) {
if (!isNaN(value)) {
this.age(value);
this.validationMessage("");
}
else {
this.validationMessage("Age must be a number!");
}
},
owner: viewModel
});
*/
var save = function(){
// var jsonData = ko.toJSON(viewModel);
// alert("Could now send this to server: " + JSON.stringify(jsonData));
$.ajax({
url: "/vacation_booking/save",
dataType: "json",
type: "POST",
data: "name=" + this.name() + "&lastName=" + this.lastName() + "&age=" + this.age(),
success: function(data){
alert("Successful");
},
failure: function(){
alert("Unsuccessful");
}
});
}
ko.applyBindings(new viewModel());
this is my view:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<h1>Testing</h1>
<p>
<a href="${pageContext.request.contextPath}/specRunner" target=_blank>Launch Test Runner</a>
</p>
First Name: <input type="text" data-bind="
value: name,
valueUpdate : 'afterkeydown'
"/>
<br />
Last Name: <input type="text" data-bind="value:lastName, valueUpdate : 'afterkeydown'" />
<br />
Age: <input type="text" data-bind="value: age, valueUpdate : 'afterkeydown'" />
<Br />
<!--p>Destination country: <select data-bind=" options : availableCountries"></select></p-->
<Br />
<span data-bind="text: validationMessage" style="color:Red"></span>
<div>
<h2>Details:</h2>
<hr />
First Name: <span data-bind="text:name"></span> <br /><br />
Last Name: <span data-bind=" text:lastName"></span><br /><br />
Age: <span data-bind="text:age"></span><br />
<button data-bind="click:save">Submit</button>
<p>Usuarios: <select data-bind="options:users, value:name" type="text"></select></p>
</div>
<script src="resources/js/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="resources/js/knockout-3.0.0.js" type="text/javascript"></script>
<script type="text/javascript" src="resources/js/viewModel.js"> </script>
</body>
</html>
don't use this.users() and use prototype for save method also.
viewModel.prototype.loadUsers = function() {
var tmp = this.users;
$.get("/vacation_booking/getUsers", function (data) {
tmp(ko.toJS(data));
log.info("Usuarios:" + data);
});
}
viewModel.prototype.save = function(){
// var jsonData = ko.toJSON(viewModel);
// alert("Could now send this to server: " + JSON.stringify(jsonData));
$.ajax({
url: "/vacation_booking/save",
dataType: "json",
type: "POST",
data: "name=" + this.name() + "&lastName=" + this.lastName() + "&age=" + this.age(),
success: function(data){
alert("Successful");
},
failure: function(){
alert("Unsuccessful");
}
});
}
second thing you can return json data directly from controller.
check this sample at fiddle

Resources