passing dropdownlist selected value to controller through html.actionlink - asp.net-mvc-3

I want to pass some values from model and dropdownlist selected value/item into controller through Html.ActionLink method, but can't find any suitable way. I am giving my code below -
View:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="row">
<div class="span3">
<div class="text-left">#Html.LabelFor(model => model.EntryId)</div>
</div>
<div class="span3">
<div class="text-left">
#Html.DisplayFor(model => model.EntryId)
#Html.HiddenFor(model => model.EntryId)
</div>
</div>
<div class="span3">
<div class="text-left">#Html.LabelFor(model => model.EntryDate)</div>
</div>
<div class="span3">
<div class="text-left">
#Html.DisplayFor(model => model.EntryDate)
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Check Information</legend>
<div class="row">
<div class="span3">
<div class="text-left">#Html.LabelFor(model => model.Check.CheckId)</div>
</div>
<div class="span3">
<div class="text-left">
#Html.DisplayFor(model => model.Check.CheckId)
#Html.HiddenFor(model => model.Check.CheckId)
</div>
</div>
<div class="span3">
<div class="text-left">#Html.LabelFor(model => model.Check.CheckTitle)</div>
</div>
<div class="span3">
<div class="text-left">#Html.DisplayFor(model => model.Check.CheckTitle)</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Comments</legend>
<div class="span4">
#Html.ActionLink("Add Comment", "AddComment", new { Model.EntryId })
#Html.ActionLink("View All Comments", "ViewAllComments", new { Model.Check.CheckId })
</div>
<div>
<table class="table table-bordered">
<tr>
<th>
Serial
</th>
<th>
Comment
</th>
<th>
Date
</th>
<th>
Status
</th>
<th>
</th>
</tr>
#for (int i = 0; i < Model.CheckCommentsList.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].Serial)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].Serial)
</td>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].Comment)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].Comment)
</td>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].CommentDate)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].CommentDate)
</td>
<td>
#Html.DropDownListFor(modelItem => Model.CheckCommentsList[i].CommentStatus, new SelectList(Model.CommentStatusList, Model.CheckCommentsList[i].CommentStatus.ToString()), new {#id="ddlCommentStatus"})
#Html.ValidationMessageFor(model => Model.CheckCommentsList[i].CommentStatus)
#*#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].CommentStatus)*#
</td>
<td>
#Html.ActionLink("Update Status", "UpdateCommentStatus", new { Model.EntryId, Model.CheckCommentsList[i].Serial, Model.CheckCommentsList[i].CommentStatus, Model.Check.CheckId })|
#Html.ActionLink("Delete", "DeleteComment", new { Model.CheckCommentsList[i].Serial, Model.EntryId })
</td>
</tr>
}
</table>
</div>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Controller:
public ActionResult UpdateCommentStatus(string entryId, int serial, string status, string checkId)
{
var securityInformation = new SecurityInformation();
securityInformation.MemberId = (string)Session["MemberId"];
if (string.IsNullOrEmpty(securityInformation.MemberId))
{
return RedirectToAction("LogIn", "MemberLogIn");
}
var commentStatus = (CommentStatus)Enum.Parse(typeof (CommentStatus), status);
new CheckDataManager().UpdateCheckDataCommentStatus(entryId, serial, commentStatus);
return RedirectToAction("ViewAllComments", new { checkId });
}
Please note that, CommentStatus is an Enum. I am always getting null for status variable in controller. Can anyone show me the way to do it. If JQuery is the solution, then please give an example as I am new at JQuery.

Related

Display Required Error message IEnumerable Model

On the same view I am returning a list. Also, I have [HttpPost] to create new entry.
When the model is not valid, The ValidationSummary shows that expenseName is Required.
I would like to show Model required error Messages near each field in my View. asp-Validation-for was working when I didn't have IEnumerable model. What I have to do so I can see the validation error messages using IEnumerable model? (etc. for expenseName)
Model
[Key]
public int expenseId { get; set; }
[Column(TypeName = "nvarchar(50)")]
[Required(ErrorMessage = "The field 'Expense Name' is required")]
public string expenseName { get; set;}
public double price { get; set; }
public bool isStandard { get; set; }
public DateTime? date { get; set; }
View
#model IEnumerable<ExpenseTracker.Models.Expenses>
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
#{
ViewData["Title"] = "Index";
}
<form method="post" enctype="multipart/form-data" asp-controller="Expenses" asp-action="Index">
<div>
<label for="files" class="lbl-select-file">Select Expense File</label>
<input id="files" name="postedFiles" class="btn-uploader" type="file">
</div>
<label class="expense-name-lbl" for="expenseName">Expense Name</label>
<input type="text" name="expenseName" class="expense-name-input" id="expenseName" />
**<span asp-validation-for=" " class="text-danger"></span>**
<div class="form-group form-check">
<label class="form-check-label checkbox-isStandard-form">
<input class="form-check-input" type="checkbox" name="chkeco" title="Check this if the bill is monthly/yearly" /> Is Standard?
</label>
</div>
<input type="submit" class="btn btn-success btnColor-expenses" value="Upload" />
<label id="fileName"></label>
<span class="uploaded-file">#Html.Raw(ViewBag.Message)</span>
</form>
<table class="table table-text">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.expenseName)
</th>
<th>
#Html.DisplayNameFor(model => model.price)
</th>
<th>
#Html.DisplayNameFor(model => model.isStandard)
</th>
<th>
#Html.DisplayNameFor(model => model.date)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.expenseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
<td>
<input type="checkbox" class="checkbox-isStandard" checked="#item.isStandard" />
</td>
<td>
#if (item.date.HasValue)
{
DateTime? datetimeToDate = #item.date;
string FormattedDate = datetimeToDate.Value.ToString("dd-MM-yyyy");
<label>#FormattedDate</label>
}
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.expenseId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.expenseId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.expenseId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
[PreventDuplicateRequest]
public async Task<IActionResult> Index(IFormCollection formCollection, string expenseName,
List<IFormFile> postedFiles, [Bind("expenseName,price,isStandard,date")] Expenses expenses)
{
if (ModelState.IsValid)
{
......
return View(await _context.Expenses.ToListAsync());
}
else
{
return View(await _context.Expenses.ToListAsync());
}
You can create a ViewModel which contains a List<Expenses>(you wanna display in the view) and a Expenses(you wanna upload to the controller).
ViewModel
public class ExpensesViewModel
{
//Pass the value to this parameter in the get method to display on the page
public List<Expenses> ListModel { get; set; }
public Expenses model { get; set; }
}
Then change your view code like:
#model ExpensesViewModel
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
#{
ViewData["Title"] = "Index";
}
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Show">
<div>
<label for="files" class="lbl-select-file">Select Expense File</label>
<input id="files" name="postedFiles" class="btn-uploader" type="file">
</div>
<div class="form-group">
<label class="expense-name-lbl" for="expenseName">Expense Name</label>
<input type="text" \ class="expense-name-input" asp-for=#Model.model.expenseName />
<span asp-validation-for="#Model.model.expenseName" class="text-danger"></span>
</div>
<div class="form-group form-check">
<label class="form-check-label checkbox-isStandard-form">
<input class="form-check-input" type="checkbox" name="chkeco" title="Check this if the bill is monthly/yearly" /> Is Standard?
</label>
</div>
<input type="submit" class="btn btn-success btnColor-expenses" value="Upload" />
<label id="fileName"></label>
<span class="uploaded-file">#Html.Raw(ViewBag.Message)</span>
</form>
<table class="table table-text">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.model.expenseName)
</th>
<th>
#Html.DisplayNameFor(model => model.model.price)
</th>
<th>
#Html.DisplayNameFor(model => model.model.isStandard)
</th>
<th>
#Html.DisplayNameFor(model => model.model.date)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.ListModel)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.expenseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
<td>
<input type="checkbox" class="checkbox-isStandard" checked="#item.isStandard" />
</td>
<td>
#if (item.date.HasValue)
{
DateTime? datetimeToDate = #item.date;
string FormattedDate = datetimeToDate.Value.ToString("dd-MM-yyyy");
<label>#FormattedDate</label>
}
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.expenseId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.expenseId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.expenseId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Finally, You can validate your expenseName property.
You can try to add this validation js.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>

Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(object value)

This is the error I get; please tell me how I can solve it:
InvalidOperationException: the model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List1[AgricultureFarming.Models.AddToCart]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable1[AgricultureFarming.Models.Order]'}
My Index View Page code I want to display product in orders index page from Addtocart model
#model IEnumerable<AgricultureFarming.Models.Order>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<div class="container">
<div class="row">
<div>
<table class="table">
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<img src="~/Images/#item.AddToCarts.Products.Image_path" class="img-fluid" style="height:50px;width:85px;" asp-append-version="true" />
</td>
<td>
<b>
#Html.DisplayFor(modelItem => item.AddToCarts.Products.Product_Name)
</b>
</td>
<td>
1 KG = #Html.DisplayFor(modelItem => item.AddToCarts.Products.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.AddToCarts.Quantity)
</td>
<td>
#(item.AddToCarts.Quantity* item.AddToCarts.Products.Price)
</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td><b>Sub Total</b></td>
<td>#Model.Sum(i => i.AddToCarts.Quantity * i.AddToCarts.Products.Price) TK</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><b>Delivery Charge</b></td>
<td><text id="DeliveryCharge"></text></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><b>Total Amount</b></td>
<td><text id="Total">#Model.Sum(i => i.AddToCarts.Quantity * i.AddToCarts.Products.Price) TK</text></td>
</tr>
</tfoot>
</table>
</div>
<div class="form-group col-md-3">
<div>
<select id="CountryList" class="form-control" asp-items="ViewBag.CountryList"></select>
</div>
<div class="form-group col-md-3"></div>
<div>
<select id="CityList" class="form-control"></select>
<br />
<text>Address:</text>
<br />
<textarea class="form-control"></textarea>
</div>
<div>
<text>Zip Code:</text>
<br />
<input type="text" name="name" value="" class="form-control"/>
</div>
</div>
</div>
</div>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="container">
<div class="row">
<div class="form-group col-md-3 align-self-start">
<select id="CountryList" class="form-control" asp-items="ViewBag.CountryList"></select>
</div>
<div class="form-group col-md-3">
<select id="CityList" class="form-control"></select>
</div>
</div>
</div>
My model class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AgricultureFarming.Models
{
public class Order
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }
[Display(Name = "Delivery Charge")]
public int DeliveryChargesId { get; set; }
[Required]
public string UserId { get; set; }
[Display(Name = "Item")]
public string AddToCartsId { get; set; }
[Required]
public string DeliveryAddress { get; set; }
[Required]
[Display(Name = "Total Price")]
[Column(TypeName = "decimal(10,2)")]
public decimal TotalAmount { get; set; }
[Required]
public DateTime OrderDate { get; set; }
public DeliveryCharge DeliveryCharges { get; set; }
public AddToCart AddToCarts { get; set; }
}
}
Your Index action returns the AddToCart collection type, so your view should use #model AgricultureFarming.Models.AddToCart to receive.
To solve this issue, change the index view code as follow:
#model IEnumerable<AgricultureFarming.Models.AddToCart>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<div class="container">
<div class="row">
<div>
<table class="table">
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<img src="~/pics/#item.Products.Image_path" class="img-fluid" style="height:50px;width:85px;" asp-append-version="true" />
</td>
<td>
<b>
#Html.DisplayFor(modelItem => item.Products.Product_Name)
</b>
</td>
<td>
1 KG = #Html.DisplayFor(modelItem => item.Products.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
#(item.Quantity* item.Products.Price)
</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td><b>Sub Total</b></td>
<td>#Model.Sum(i => i.Quantity * i.Products.Price) TK</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><b>Delivery Charge</b></td>
<td><text id="DeliveryCharge"></text></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><b>Total Amount</b></td>
<td><text id="Total">#Model.Sum(i => i.Quantity * i.Products.Price) TK</text></td>
</tr>
</tfoot>
</table>
</div>
<div class="form-group col-md-3">
<div>
<select id="CountryList" class="form-control" asp-items="ViewBag.CountryList"></select>
</div>
<div class="form-group col-md-3"></div>
<div>
<select id="CityList" class="form-control"></select>
<br />
<text>Address:</text>
<br />
<textarea class="form-control"></textarea>
</div>
<div>
<text>Zip Code:</text>
<br />
<input type="text" name="name" value="" class="form-control" />
</div>
</div>
</div>
</div>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="container">
<div class="row">
<div class="form-group col-md-3 align-self-start">
<select id="CountryList" class="form-control" asp-items="ViewBag.CountryList"></select>
</div>
<div class="form-group col-md-3">
<select id="CityList" class="form-control"></select>
</div>
</div>
</div>```
Here is the test result:

create and index views combined in 1 view

I want to be able to add players and upon addition in the same I want to display them in a table similar to what page Index view offers. so what I did is combine the index and create views in 1 page.
but when debugging I'm have a resource cannot be found error.
can some one please correct where I'm going wrong
Index View:
#model IEnumerable<sportsMania.player>
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>category</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.Label("Player Name")
<div class="col-md-10">
#Html.Editor("Player Name")
</div>
</div>
<div class="form-group">
#Html.Label("Team")
<div class="col-md-10">
#Html.DropDownList("team", ViewBag.team as SelectList)
</div>
</div>
<div class="form-group">
#Html.Label("Position")
<div class="col-md-10">
#Html.Editor("position")
</div>
</div>
<div class="form-group">
#Html.Label("Email")
<div class="col-md-10">
#Html.Editor("email")
</div>
</div>
<div class="form-group">
#Html.Label("Type")
<div class="col-md-10">
#Html.Editor("type")
</div>
</div>
<div class="form-group">
#Html.Label("Height")
<div class="col-md-10">
#Html.Editor("height")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.playerName)
</th>
<th>
#Html.DisplayNameFor(model => model.team)
</th>
<th>
#Html.DisplayNameFor(model => model.position)
</th>
<th>
#Html.DisplayNameFor(model => model.email)
</th>
<th>
#Html.DisplayNameFor(model => model.type)
</th>
<th>
#Html.DisplayNameFor(model => model.height)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.playerName)
</td>
<td>
#Html.DisplayFor(modelItem => item.team)
</td>
<td>
#Html.DisplayFor(modelItem => item.position)
</td>
<td>
#Html.DisplayFor(modelItem => item.email)
</td>
<td>
#Html.DisplayFor(modelItem => item.type)
</td>
<td>
#Html.DisplayFor(modelItem => item.height)
</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>
playerController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace sportsMania.Controllers
{
public class playerController : Controller
{
sportsEntities db = new sportsEntities();
[HttpPost]
public ActionResult Index()
{
var data = from p in db.Teams
select p.teamName;
SelectList list = new SelectList(data);
ViewBag.team = list;
return View(db.players.ToList());
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(player player)
{
if (ModelState.IsValid)
{
player newRecord = new player();
newRecord.playerName = Request.Form["Player Name"];
newRecord.position = Request.Form["position"];
newRecord.type =Request.Form[ "type"];
newRecord.team =Request.Form[ "team"];
newRecord.email = Request.Form["email"];
newRecord.height = Request.Form["height"];
db.players.Add(player);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(player);
}
}
}
why I am doing this? because I don't want every time the user have to add a Player he should be redirected to the create view, I want when user finishes adding players he will hit a button "done adding" and will be redirected home.

Partial view renders as full view

MVC 3 , ajax, c#
My partial view is rendering as a new page instead of replacing the search results table.
Controller:
public class SearchController : Controller
{
//
// GET: /Search/
private myEntities db = new myEntities();
private Repository repo = new Repository();
[HttpGet]
public ActionResult Index()
{
var model = new List<PersonViewModel>();
model = repo.GetPeople();
return View(model);
}
public PartialViewResult _SearchResult(string fname, string lname)
{
var personResult = repo.GetSearchResult(fname, lname);
return PartialView("_SearchResult", personResult);
}
}
The view:
<div class="page">
<div class="middle-col-comment-mod">
<h2>Search Existing Trespassers</h2>
<div id="search">
#using (Ajax.BeginForm("_SearchResult", "Search", null, new AjaxOptions { HttpMethod = "Post", InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, UpdateTargetId = "indexSearchResults" }))
{
<div class="editor-field">
<label>First Name:</label>
#Html.TextBox("FirstName")
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBox("LastName", "", new { style = "margin-right: 15px;" })
<input type="submit" name="submit" class="skbutton" value="Search" />
</div>
}
</div>
<table id="indexSearchResults" class="data-table">
<tr>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Gender
</th>
<th>
City
</th>
<th>
DOB
</th>
<th>
IsStudent
</th>
<th>
Actions
</th>
</tr>
#if (Model.Count() == 0)
{
<tr>
<td colspan=7>
There are currently no trespassers in the trespass database.
</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
#Html.DisplayFor(modelItem => item.DOB)
</td>
<td>
#Html.DisplayFor(modelItem => item.School)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsStudent)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.PersonId }) |
#Html.ActionLink("Details", "Details", new { id = item.PersonId }) |
#Html.ActionLink("Delete", "Delete", new { id = item.PersonId })
</td>
</tr>
}
}
</table>
</div>
</div>
And the partial view:
#model IEnumerable<TrespassTracker.Models.PersonViewModel>
<table>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Gender
</th>
<th>
Date of Birth
</th>
<th>
Is a Student?
</th>
<th>
Actions
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
#Html.DisplayFor(modelItem => item.DOB)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsStudent)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
From my research I found the usual suspect to be the missing link to the jquery script in the partial, but I had that. I checked the network tab on my wed dev tools and found it is being called. What else could the problem be?
the script won't cause any problem and the only thing I see wrong here is the table. you are trying yo fill the table with other table which returns a table, use a div instead to update the ajax form (search result):
<div id="indexSearchResults">
<table>
..........
</table>
</div>
Try this
<div class="page">
<div class="middle-col-comment-mod">
<h2>Search Existing Trespassers</h2>
<div id="search">
#using (Ajax.BeginForm("_SearchResult", "Search", null, new AjaxOptions { HttpMethod = "Post", InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, UpdateTargetId = "indexSearchResults" }))
{
<div class="editor-field">
<label>First Name:</label>
#Html.TextBox("FirstName")
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBox("LastName", "", new { style = "margin-right: 15px;" })
<input type="submit" name="submit" class="skbutton" value="Search" />
</div>
}
</div>
#if (Model.Count() == 0)
{
<label>There are currently no trespassers in the trespass database. </label>
}
else
{
foreach (var item in Model)
{
#Html.Partial("__SearchResult",item)
}
</div>
</div>
How 'bout to use jQuery do reload your result content, instead Post from your form? You can named some div with an ID and uses it as reference do jQuery.load() (considering you're using that ViewModel you passed into Index action):
1.View
#model YourModel
<!-- ... -->
<div id="search">
#using (Ajax.BeginForm("MainPostAction", "ControllerName", FormMethod.Post, new { id = "yourFormID" })
{
<div class="editor-field">
<label>First Name:</label>
#Html.TextBoxFor(model => model.FirstName)
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBoxFor(model => model.LastName, new { style = "margin-right: 15px;" })
<input type="button" name="submit" id="searchButton" class="skbutton" value="Search" />
</div>
<div id="results"></div>
}
</div>
Javascript:
$(document).ready(function() {
$('#searchButton').click(function(event) {
$('#results').load('#Url.Action('_SearchResult', 'Search')', $('#yourFormID').serialize());
});
}
Your action remains the same.
How 'bout it?

MVC 3 using partial view to add a new listing with ajax

REVISED BUT SAME ISSUE:
I am building a site with MVC 3 and have run into a big road block. On the profile page, users will have the ability to create a new listing offered by their center. I have created this using a partial view for the "_CenterProfile" portion of the page which works perfectly. I've implemented the Create Listing as the main focus of the page and model which also works perfectly. I would like to use Ajax to create the database entries as well as populate or update the Listings shown on the Profile page. This is where the problem comes in.
When I click the submit button, rather than updating the targeted element, the page flips to a non existent "CreateListing" page ../Exchange/CreateListing. I'm going crazy trying to get this to function and no matter what I try it does the same thing. The Listing is populated to the database and the page changes from /Exchange/Profile to /Exchange/CreateListing.
I'm sure someone out there can help me, I'm on a deadline and getting past this headache will save me big time.
"Profile" View:
#model Exchange.Models.CreateListingModel
#{
ViewBag.Title = "Profile";
}
<h2>Profile</h2>
#Html.Action("_CenterProfile")
<br />
#using (Ajax.BeginForm("CreateListing", "Exchange", new AjaxOptions
{
HttpMethod = "Get",
UpdateTargetId = "centerListings",
InsertionMode = InsertionMode.Replace
}))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>CreateListingModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.productName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.productName)
#Html.ValidationMessageFor(model => model.productName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.forSale)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.forSale)
#Html.ValidationMessageFor(model => model.forSale)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.forTrade)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.forTrade)
#Html.ValidationMessageFor(model => model.forTrade)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.price)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.price)
#Html.ValidationMessageFor(model => model.price)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.unit)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.unit)
#Html.ValidationMessageFor(model => model.unit)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.catagoryID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.catagoryID)
#Html.ValidationMessageFor(model => model.catagoryID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.description)
#Html.ValidationMessageFor(model => model.description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.imageURL)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.imageURL)
#Html.ValidationMessageFor(model => model.imageURL)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.activeListing)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.activeListing)
#Html.ValidationMessageFor(model => model.activeListing)
</div>
</fieldset>
<p>
<input type="submit" value="CreateListing" />
</p>
}
<table id="centerListings">
</table>
<p>
#Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
#Html.ActionLink("Back to List", "Index")
</p>
CreateListing Controller:
public PartialViewResult CreateListing(CreateListingModel model)
{
mmjc.CreateListing(model.catagoryID, model.productName, model.forSale, model.forTrade, model.price, model.unit, model.description, model.imageURL, model.activeListing);
var listings = mmjc.GetCenterListings();
return PartialView("_CenterListings", listings);
}
_CenterListings PartialView:
#model IEnumerable<Exchange.Models.Listing>
<table id="centerListings">
<tr>
<th>
CatagoryID
</th>
<th>
ProductName
</th>
<th>
ToSell
</th>
<th>
ToTrade
</th>
<th>
PricePerUnit
</th>
<th>
Unit
</th>
<th>
Description
</th>
<th>
ImgPath
</th>
<th>
ProfileID
</th>
<th>
ActiveListing
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.CatagoryID)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ToSell)
</td>
<td>
#Html.DisplayFor(modelItem => item.ToTrade)
</td>
<td>
#Html.DisplayFor(modelItem => item.PricePerUnit)
</td>
<td>
#Html.DisplayFor(modelItem => item.Unit)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.ImgPath)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProfileID)
</td>
<td>
#Html.DisplayFor(modelItem => item.ActiveListing)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ListingsID }) |
#Html.ActionLink("Details", "Details", new { id=item.ListingsID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ListingsID })
</td>
</tr>
}
</table>
I think you should provide an UpdateTargetId in your AjaxOptions:
new AjaxOptions { HttpMethod = "Post",
UpdateTargetId = "idOfSomeHtmlContainer" }
With this property you specify which part of the page should be updated with the response from the AJAX call. Using the code you have now, ASP.NET MVC doesn't know which part of the page to update with the view returned from your action method.
Ok everyone. So I fixed my own problem here. It seems many people are having this same issue. The fix is so easy it made me feel very silly.
All you have to do is include
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
In your _Layout or Main View. Without it the Ajax.BeginForm is useless and will continue to redirect to the PartialViewResult.
I think you want to specify the necessary Ajax options to replace the content of the create listing form- namely the Id of the element to replace and the update mode.

Resources