display model contents dynamically in View MVC4 - ajax

I have a homepage that will display a table with some data for each user. The back-end handles that and I have a list in my model. I am trying to view a dynamic table based on this list and be able to delete elements from without having to hit refresh. I do not know where to start to do something like this. Any help?
Here is what I have so far:
Inside HomePage controller I have an action returning Json representation of the model. Have of 'HpModel' gets set in the login controller and the other is in this one:
public JsonResult GetUserInfo(HomePageModel HpModel)
{
DBOps ops = new DBOps();
HpModel.PhoneDisplay = ops.getDisplayInfo(HpModel.ExtNum);
HpModel.NumberOfLines = HpModel.PhoneDisplay.Count;
return Json(HpModel);
}
In my view I have a javascript to grab this model:
function getInfo() {
alert('here');
$.ajax({
url: '#Url.Action("GetUserInfo", "HomePage")',
data: json,
type: 'POST',
success: function (data) {
alert(data);
}
});
}
I am not sure what is going wrong, and not 100% sure its the way to be done anyway.
Help is appreciated :)

One more idea. You may use jQuery to hide and callback function to $Post to your Delete ActionResult.
For examp: (here I created easy example without $post: jsfiddle)
<script>
$('.delete').click(function()
{
$(this).closest('tr').hide(callback);
function callback() {
$post(/Home/Delete/....
});
</script>
<table>
<tr>
<td>Marry</td>
<td>10 points</td>
<td><a class="delete" href="#">Delete</a></td>
</tr>
<tr>
<td>Jane</td>
<td>8 points</td>
<td><a class="delete" href="#">Delete</a></td>
</tr>
<tr>
<td>Lara</td>
<td>5 points</td>
<td><a class="delete" href="#">Delete</a></td>
</tr>
</table>

Related

Jquery ajax form submit that contains files

I have a very long form that contains files attachment:
this is how my form looks like:
The form will be submitted to this action:
[HttpPost]
public ActionResult AddReceivingConfirm(DTOreceiving entry,IEnumerable<HttpPostedFileBase> fileUpload)
{
return PartialView();
}
through ajax call which is:
$(document).on('click', 'input[type="submit"].genericSubmit', function () { //generic function for ajax submit of ANY FORMS t
if (!$("form#ValidateForm").valid()) {
return false;
};
var frmData = $('.genericForm').serialize();
var frmUrl = $('.genericForm').attr('action');
$.ajax({
type: 'post',
url: frmUrl,
data: frmData,
success: function (e) {
$('#target').html(e);
}
});
return false;
});
everything is binding perfectly except the IEnumerable<HttpPostedFileBase>which always results to null,
the file part of my form is done like this:
<tr>
<td>Attachment #1: </td>
<td colspan="3">
<input id="file1" type="file" name="fileUpload" />
</td>
</tr>
<tr>
<td>Attachment #2: </td>
<td colspan="3">
<input id="file2" type="file" name="fileUpload" />
</td>
</tr>
<tr>
<td>Attachment #3: </td>
<td colspan="3">
<input id="file3 "type="file" name="fileUpload" />
</td>
</tr>
I have tried the brackets version and etc but it won't bind.
After an hour of researching, i've read that it's not possible(?) )to do file posting conventionally through the use of Ajax unless iframe. I am not sure of what my action will be, i kinda want to avoid using plugin so i wanna know if there is some "hacky" ways to access the files directly from my form?
this is my form:
using (Html.BeginForm("AddReceivingConfirm", "Wms", FormMethod.Post, new { id = "ValidateForm", #class = "genericForm" , enctype="multipart/form-data"}))
Unfortunately the jQuery serialize() method will not include input file elements. So your files are not going to be included in the serialized value.
What you should be doing is creating a FormData object, append the files to that. You need to append the form field values as well to this same FormData object. You may simply loop through all the input field and add it. Also, in the ajax call, you need to specify processData and contentType property values to false.
$(document).on('click', 'input[type="submit"].genericSubmit', function(e) {
e.preventDefault(); // prevent the default submit behavior.
var fdata = new FormData();
$('input[name="fileUpload"]').each(function(a, b) {
var fileInput = $('input[name="fileUpload"]')[a];
if (fileInput.files.length > 0) {
var file = fileInput.files[0];
fdata.append("fileUpload", file);
}
});
// You can update the jquery selector to use a css class if you want
$("input[type='text'").each(function(x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
var frmUrl = $('.genericForm').attr('action');
$.ajax({
type: 'post',
url: frmUrl,
data: fdata,
processData: false,
contentType: false,
success: function(e) {
$('#target').html(e);
}
});
});
Seems like your $.ajax needs contentType: false to prevent a bad content-type header from being inserted.
Also, if I am reading the docs ( https://api.jquery.com/serialize/ ) correctly .serialize skips file inputs...
This answer also seems helpful How can I upload files asynchronously?

ASP.NET MVC partial view refresh on button click

I'm using VS 2013, MVC 5.
Here is the content of my partial view (_Sales.cshtml):
#model IEnumerable<SomeModel>
<div id="outer">
<div id="inner1">
#(Html.Kendo().Chart<SomeModel>(Model)
...
)
</div>
<div id="inner2">
<table>
<tr>
<td>Total Sales </td>
<td>#Model.First().TotalSales.ToString("C")</td>
</tr>
<tr>
<td>Total Discount </td>
<td>#Model.First().TotalDiscount.ToString("C")</td>
</tr>
</table>
</div>
</div>
Below is an action method used while loading first time:
public ActionResult _Sales()
{
IEnumerable<SomeModel> salesList = null;
SearchCriteriaObject criteria = null;
salesList = getting data as list;
return PartialView(salesList);
}
So far, all work fine as expected. That's my partial view is rendering fine with initial data.
Now my requirement is I need to refresh my partial view as user specify search criteria and hit search button.
Here is the search button specific action method:
public ActionResult Get_BulletChartData_Updated(SearchViewModel criteriaModel)
{
IEnumerable<SomeModel> salesList = null;
SearchObject criteria = new SearchObject();
if (ModelState.IsValid)
{
if (criteriaModel != null)
{
//populating criteria here
}
salesList = //Getting data in list format
}
return PartialView(salesList);
}
On search button click event handler in javascript, I do this:
$("#btnSearch").click(function () {
...
var Url = $('#Url').val(); //Getting action method url from hidden field
$.ajax({
type: "POST",
dataType: 'HTML',
data: JSON.stringify(SearchViewModel),
url: Url, //#Url.Action("Get_SalesDataFiltered", "Sales")
contentType: "application/json; charset=utf-8",
success: function (result)
{
alert('success');
//$("#outer").load(result);
},
error: function ()
{
alert("error");
}
});
On search button click, I always get error alert message.
Could you please guide me the correct way to achieve this.
I'm new to MVC. Please feel free to ask for more info.
If you provide me with code, it'd be great.
Thanks.
I think that your problem is that you post a json object, while your post method has as a parameter a SearchViewModel object.
I believe that If you change this
data: JSON.stringify(SearchViewModel)
to this
data: $("#yourFormId").serialize()
you will get the expected result.

Redirect in ASP.Net MVC4

I'm using ASP.Net MVC4 Razor. I'm having a problem with redirection. I wanna redirect the user to the Home controller at the user login(if login is valid).
But my problem is it always come back to the login page even the redirect meythod also fired.
Here is my code..
public class LoginController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult LoginAccess()
{
return RedirectToAction("Index", "Home");
}
}
Login page..
<div class="body_wraper">
<div id="cloud" style="background:url('#Url.Content("~\\Content\\cloud.png")');">
<div id="login_form">
<div class="Three-Dee">Login here..</div>
<table>
<tbody>
<tr>
<td>#Html.Label("Username")</td>
<td></td>
<td>#Html.TextBox("txtUsername")</td>
</tr>
<tr>
<td>#Html.Label("Password")</td>
<td></td>
<td>#Html.Password("txtPassword")</td>
</tr>
<tr>
<td></td>
<td></td>
<td style="text-align:right;"><button class="k-button" id="login" onclick="Login()">Login</button></td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
function Login() {
$.ajax({
url: '#Url.Content("~/Login/LoginAccess")',
type: 'POST'
});
}
Home Controller..
public ActionResult Index()
{
Session["UserName"] = "Administrator";
string menu = this.GetMenu();
ViewBag.ManueItems = menu;
return View("User");
}
After click on the login button it comes to LoginAccess in Login controller and then comes to Home controller Index method, but doesn't view the "user view".
But when i check with typing url >>(host__/Login/LoginAccess">http://__host__/Login/LoginAccess) Its working properly.
Please help me to slove this problem.
Thank you.. :)
You may misuse the Ajax function here
You should use #Html.ActionLink("Login", "LoginAccess", "Login") instead
Ajax is originally used to get something from server side other than affecting currently browsing page.
When you are doing Ajax calls, you cannot force redirect from controller. You can fix this by 2 ways:
Replace ajax call with regular get.
Return a json from the action and use redirect from javascript
try this instead
return redirect("/Home/Index")
You can try this
var result = new ControllerName().YourAction();

How to POST to database through URL

I'm writing a web application in Spring/Hibernate that handles basic voting functionality. I want to have a link to /vote/{gameId} which will add that vote to the database for that specific ID. I'm really at a loss as for how to accomplish this though. Here's what I've tried in my controller:
#RequestMapping(value="/vote/{gameId}", method = RequestMethod.POST)
public String addVote(#PathVariable("gameId")
Integer gameId) {
Vote vote = new Vote();
vote.setGameId(gameId);
voteService.addVote(vote);
return "redirect:/games/wanted.html";
}
Here's where the link shows up in a jsp:
<c:if test="${!empty games}">
<table>
<tr>
<th>Game Title</th>
<th>Votes</th>
<th> </th>
</tr>
<c:forEach items="${games}" var="game">
<tr>
<td><c:out value="${game.title}"/></td>
<td>Placeholder</td>
<td>Vote!</td>
</tr>
</c:forEach>
</table>
</c:if>
When I try this though I just get a 404 error. Any insight would be great.
This is how you make a post call with plain Javascript:
var url = "vote";
var params = "id=1";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
You need to call this in the onclick of your link.
On the other hand it is a lot easier if, for example, you use the jQuery Javascript library:
For your particular case it would be something like:
$.post("vote", { id: "1" } );
Or the full jQuery answer (remember to replace #linkid with the id of you tag):
$(document).ready(function() { //this runs on page load
// Handler for .ready() called.
$('#linkid').click(function(event) { //this finds your <a> and sets the onclick, you can also search by css class by type of tag
$.post("vote", { id: "1" } );
return false; //this is important so that the link is not followed
});
});

Partial view in MVC3 Razor view Engine

I have an view in MVC3 Razor view engine like following image. Now i want to Confirm Connection Action Output show under this link text not New page. How can i done this work?
Please explain with example code.
My View Like this :
#model ESimSol.BusinessObjects.COA_ChartsOfAccount
#{
ViewBag.Title = "Dynamic Account Head Configure";
}
<h2>Dynamic Account Head Configure</h2>
<table border="0">
<tr>
<td> Select an Server Connection </td>
<td style="width:5px">:</td>
<td>#Html.DropDownListFor(m => m.DBConnections, Model.DBConnections.Select(x => new SelectListItem() { Text = x.ConnectionName, Value = x.DBConnectionID.ToString()}))</td>
</tr>
<tr>
<td> </td>
<td style="width:5px"></td>
<td>#Html.ActionLink("Confirm Connection", "ConformConnection")</td>
</tr>
</table>
AND My Controller action Like following :
public ActionResult ConfirmConnection()
{
return PartialView();
}
I'm a big fan of using jquery and ajax for this kind of thing ...
http://api.jquery.com/jQuery.ajax/
If you are following the typical MVC model then you can add an action link to the page using something like ...
#Html.ActionLink("controller", "action", args);
but I would go for the ajax driven approach ...
<script type="text/javascript">
var ajaxBaseUrl = '#Url.Action("yourController", "ConformConnection", new { args })';
$(link).click(function () {
var currentElement = $(this);
$.ajax({
url: ajaxBaseUrl,
data: { any other queryString stuff u want to pass },
type: 'POST',
success: function (data) {
// action to take when the ajax call comes back
}
});
});
});
</script>
First move your markup to a partial view. After that define an action method that renders your partial view.
[ChildActionOnly]
public ActionResult ConfirmConnection(COA_ChartsOfAccount model)
{
return PartialView("MyPartialView", model);
}
ChildActionOnly attribute makes sure this action method cannot be called by a HTTP request.
Then you can display it whenever you want using Html.Action method.
#Html.Action("ConfirmConnection", "MyController", new { model = Model })
Ignore passing the model as a parameter if it doesn't change by the page you display it. You can retrieve it in your action method.

Resources