Javascript function argument is not showing in Asp.Net MVC RouteValueDictionary? - c#

I am new bee to Asp.net. I like to pass an id of an entity to edit method in controller through view. Here is my code.
#
#model IEnumerable<Login.DAL.tabLogin>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div id="work_area">
</div>
<table>
<tr>
<th>
Username
</th>
<th>
Password
</th>
<th>
Email
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Username)
</td>
<td>
#Html.DisplayFor(modelItem => item.Password)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
Edit|
#Html.ActionLink("Details", "Details", new { id=item.UserID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.UserID })
</td>
</tr>
}
</table>
<script type="text/javascript" language="javascript">
function editUser(idval) {
alert(idval);
$('#work_area').load('#Url.Action("Edit","Home", new RouteValueDictionary(new { id = idval}))');
}
</script>
I did not get the correct functionality .
$('#work_area').load('#Url.Action("Edit","Home", new RouteValueDictionary(new { id = 1}))');
If I hard code the id value as above , It is working as expected. Please help me on this.

The problem is that you're mixing Razor and JavaScript and don't have an understanding of what happens where/when. The line of code:
$('#work_area').load('#Url.Action("Edit","Home", new RouteValueDictionary(new { id = 1}))');
will render as a completed URL before the javascript is rendered. That means, once the page is loaded by the browser, that line already says:
$('#work_area').load('http://example.com/home/edit/1');
and will never change based on javascript. To get the javascript parameter into your URL, you'll have to combine the URL from Razor with a javscript parameter. Try something like:
function editUser(idval) {
alert(idval);
var baseUrl = '#Url.Action("Edit","Home")';
$('#work_area').load(baseUrl + '/' + idval);
}

Related

I am receiving a Server error on on the controller on my ASP.NET MVC app

I have an ASP.NET MVC application that I have created. The data displays fine however I get an error which you can see below:
I have created the views and controllers fine however on 2 out of the 5 views / index there is an issue when performing a search via the controller I get an error.
Below is the search functionality I have added to the controller
public AppSupportEntities db = new AppSupportEntities();
// GET: Servers
public ActionResult Index(string searchBy, string search)
{
if (searchBy == "NAME")
{
return View(db.Servers.Where(x => x.NAME.StartsWith(search) || search == null).ToList());
}
else
{
return View(db.Servers.Where(x => x.DESCRIPTION.StartsWith(search) || search == null).ToList());
}
}
This is the search functionality added to the index page on the view
#model IEnumerable<ADSTrepo.Models.Server>
#{
ViewBag.Title = "Index";
}
<h2>Server List</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<p>
#using (Html.BeginForm("Index", "Server", FormMethod.Get))
{
<b>Search By:</b> #Html.RadioButton("searchBy", "Name") <text>Name</text>
#Html.RadioButton("searchBy", "Description") <text>Description</text>
#Html.TextBox("Search")<input type="submit" value="Search" />
}
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.DESCRIPTION)
</th>
<th></th>
</tr>
#if (Model.Count() == 0)
{
<tr>
<td colspan="2"> No rows match the search criteria please try again</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.DESCRIPTION)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
}
</table>
Any help is greatly appreciated I must be missing something obvious however the views and controllers seem fine and the same as the others that are working
This has been resolved now. The searchy by name in my controller was different to whats in my view.

Whats the best way of using ajax jquery to load partial views onto a specific page?

I have a index page the code looks like this
#model PagedList.IPagedList<PartialViews.Models.Customer>
#using PagedList.Mvc
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div class="container">
<table class="table">
<tr>
<th>
Title
</th>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Email Address
</th>
<th>
Phone Number
</th>
<th>
Modified Date
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
#Html.DisplayFor(modelItem => item.ModifiedDate)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.CustomerID }) |
#Html.ActionLink("Details", "Details", new { id = item.CustomerID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.CustomerID })
</td>
</tr>
}
</table>
#Html.PagedListPager(Model,page=>Url.Action("Index",new{page,pageSize=Model.PageSize}))
</div>
My CustomersController has this code
private AdventureWorksLT2012Entities db = new AdventureWorksLT2012Entities();
// GET: Customers
public ActionResult Index(int page=1, int pageSize=10)
{
List<Customer> customers = db.Customers.ToList();
PagedList<Customer> cust = new PagedList<Customer>(customers,page,pageSize);
return View(cust);
//return View(db.Customers.ToList());
}
Heres the Main page where i want the Customers List from the Index action to be shown
#model PartialViews.Models.Customer
#{
ViewBag.Title = "Main";
}
<body>
<div class="container">
<h2>Customer's List</h2>
<div id="dvCustomerDetails" style="width: 50%; height: 130px;display: none"></div>
</div>
</body>
<script type="text/javascript">
$.ajax({
url: 'Customers/Index',
contentType: 'application/html;',
type: 'GET',
dataType:'html'
})
.success(function(result) {
$('#dvCustomerDetails').html(result);
})
</script>
I want to display this table onto a new page as a partial view using ajax jquery but I am having trouble implementing it.
I was able to use RenderPartial method to display it as a partial view but i am having trouble doing it with ajax. Any help or suggestion will be appreciated.

Using sql command with controller in view

INSERT INTO SaleItem (ProdId, SaleQuantity) SELECT ProdId, BasketProdQuantity FROM Basket;
This is my SQL command and I want to use it with a button on a view. But I don't know how to references method with button on view. And should I use SqlConnection connection = new SqlConnection(connectionString) I already connect my DB with WebConfig and it connected as DefaultConnection.
EDIT:
I'm new at MVC and Web coding so I don't know what to do.
[HttpPost]
public ActionResult Buy(SaleItem saleitem)
{
if (ModelState.IsValid)
{
string query = "INSERT INTO SaleItem (ProdId, SaleQuantity) SELECT ProdId, BasketProdQuantity FROM Basket";
db.Database.ExecuteSqlCommand(query);
db.SaveChanges();
return RedirectToAction("Index", "Basket");
}
return View(saleitem);
}
and there is the view that I want to use buy method.
#model IEnumerable<VeriPark001.Models.Basket>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Product.Book.BookName)
</th>
<th>
#Html.DisplayNameFor(model => model.BasketProdQuantity)
</th>
<th>
#Html.DisplayNameFor(model => model.Product.ProdPrice)
</th>
<th>
Total
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Product.Book.BookName)
#Html.DisplayFor(modelItem => item.Product.MovieDVD.DVDName)
#Html.DisplayFor(modelItem => item.Product.MusicCD.CDName)
</td>
<td>
#Html.DisplayFor(modelItem => item.BasketProdQuantity)
</td>
<td>
#Html.DisplayFor(modelItem => item.Product.ProdPrice)
</td>
<td>
#(item.Product.ProdPrice * item.BasketProdQuantity)
</td>
<td>
<button>#Html.ActionLink("Delete", "Delete", new { id = item.BasketId })</button>
<button>#Html.ActionLink("Update quantity", "Edit", new { id = item.BasketId })</button>
</td>
</tr>
}
</table>
<p>
<button>I WANT TO CALL ACTION HERE. I search for how to do that and couldn't find a proper way.</button>
<button>#Html.ActionLink("Products", "Index", "Product")</button>
</p>
You can use Html.BeginForm and send a post request to your controller action.
Replace your
<p>
<button>I WANT TO CALL ACTION HERE. I search for how to do that and couldn't find a proper way.</button>
<button>#Html.ActionLink("Products", "Index", "Product")</button>
</p>
with
#using (Html.BeginForm("Buy", "YourController", FormMethod.Post))
{
// Input for your SaleItem model
<button class="btn btn-group btn-group-sm" type="submit">Submit</button>
}
Since your Buy action requires a SaleItem model I'll leave it up to you.

ASP.NET MVC save button loading but not working

I have implemented a save button in my .NET application on the index page. When I click it, it loads, but does not save anything. I am just using the index page for checkboxes. If I uncheck something and save it, it saves, but also unchecks everything else in that row. Nothing happens when I try to check something. Here is the code I'm using:
Index.cshtml
#using (Html.BeginForm("save", "drnos"))
{
<input type="submit" value="Save" />
}
An example of one of my check box fields:
<td>
#Html.EditorFor(modelItem => item.Soft)
#Html.ValidationMessageFor(modelItem => item.Soft)
</td>
drnosController.cs
[HttpPost]
public ActionResult save(Doctor doc)
{
System.Diagnostics.Debug.WriteLine("Save Called");
db.Entry(doc).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
Here is the whole HTML file:
#model PagedList.IPagedList<drnosv6.Models.Doctor>
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Index";
}
<h2>Doctors</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm()) //insert the search bar
{
<p>
Find by First Name, Last Name, or RVH ID: #Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
}
#using (Html.BeginForm("save", "drnos"))
{
<input type="submit" value="Save" />
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('tr:even').addClass('alt-row-class');
});
</script>
<p>
</p>
<p>Click on a column header to sort by that column</p>
<table>
<tr>
<th>
#Html.ActionLink("RVH ID", "Index", new { sortOrder = ViewBag.IDSortParm })
</th>
<th>
#Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.LastSortParm })
</th>
<th>
#Html.ActionLink("First Name", "Index", new { sortOrder = ViewBag.FirstSortParm })
</th>
<th>
Middle Initial
</th>
<th>
Degree
</th>
<th>
Group
</th>
<th>
Adm Priv
</th>
<th>
#Html.ActionLink("QCPR", "Index", new { sortOrder = ViewBag.QCPRSortParm })
</th>
<th>
#Html.ActionLink("Keane", "Index", new { sortOrder = ViewBag.KeaneSortParm })
</th>
<th>
#Html.ActionLink("Orsos", "Index", new { sortOrder = ViewBag.OrsosSortParm })
</th>
<th>
#Html.ActionLink("Soft", "Index", new { sortOrder = ViewBag.SoftSortParm })
</th>
<th>
#Html.ActionLink("3M", "Index", new { sortOrder = ViewBag.threeMSortParm })
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
using (Html.BeginForm("Save", "Doctor", FormMethod.Post))
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.RVH_ID_)
</td>
<td>
#Html.DisplayFor(modelItem => item.Last_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.First_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Middle_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Degree1)
</td>
<td>
#Html.DisplayFor(modelItem => item.Group)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdmPriv)
</td>
<td>
#Html.DisplayFor(modelItem => item.QCPR)
</td>
<td>
#Html.EditorFor(modelItem => item.Keane)
#Html.ValidationMessageFor(modelItem => item.Keane)
</td>
<td>
#Html.EditorFor(modelItem => item.Orsos)
#Html.ValidationMessageFor(modelItem => item.Orsos)
</td>
<td>
#Html.EditorFor(modelItem => item.Soft)
#Html.ValidationMessageFor(modelItem => item.Soft)
</td>
<td>
#Html.DisplayFor(modelItem => item.C3M)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.RVH_ID_ })
#Html.ActionLink("Details", "Details", new { id = item.RVH_ID_ })
</td>
</tr>
}
}
</table>
<p>
<input type="submit" value="Save" />
</p>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
Your BeginForm or ActionLink has to point to ActionResult Edit.
When a form is submitted, only the inputs declared within that form get submitted. You only have the submit button in your form, so there are no other fields to fill out your Doctor structure. You need to have your save button on the same form as all your other fields.

MVC3 Display the edit view on the same page as the list of items

I have a list of transactions. When I click one of them, I'd like to be able to display the edit form (populated with the selected item's data) to the right of the list. Any ideas?
Below is the partial view that displays the list of transactions.
#model IEnumerable<BudgetPlus.Models.Transaction>
#{
ViewBag.Title = "Index";
}
<p>
#Html.ActionLink("Create New", "Create", null, new { #class = "button-link" })
</p>
<table>
<thead>
<tr>
<th class="column-Date">Date</th>
<th class="column-Description">Description</th>
<th class="column-Category">Category</th>
<th class="column-Amount">Amount</th>
<th class="action-button"></th>
<th class="action-button"></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category.DisplayName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Amount)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id })
</td>
<td>
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</tbody>
</table>
<div>
#Html.EditorForModel("Edit")
</div>
And this is what the edit method in my TransactionController looks like.
public ActionResult Edit(int id)
{
Transaction transaction = db.Transactions.Find(id);
ViewBag.CategoryId = new SelectList(db.Categories, "Id", "DisplayName", transaction.CategoryId);
return View(transaction);
}
Probably the easiest way to achieve this is to use Ajax.Actionlink helper.
In your for loop have this instead of Html.Actionlink:
#Ajax.ActionLink("Edit", "Edit", new { id=item.Id }, new AjaxOptions { UpdateTargetId = "editor", HttpMethod = "Get", InsertionMode = InsertionMode.Replace });
And on the right side of your table:
<div id="editor"></div>
Then have a partial view for editing the Transaction, which will be rendered into the div with id "editor". You are using EditorForModel helper so I assume you have a partial view for editing already.
In your actionmethod return the partial view instead:
return PartialView("YourPartialView", transaction);

Categories

Resources