Insert Partial View to a another Partial View - asp.net-mvc-4

This is the main view Dept_Manager_Approval.cshtml where I have put a modal to show data.
<td>
<i title="View Details">
#Ajax.ActionLink(" ", "ViewAccessStatus", new { id = item.request_access_id },
new AjaxOptions
{
HttpMethod = "Get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "edit-div",
}, new { #class = "fa fa-eye btn btn-success approveModal sample" })</i>
</td>
In this partial view which just a modal, ViewAccessStatus.cshtml , I have inserted in here another partial view.
<div>
<h2><span class ="label label-success">Request Creator</span> </h2>
#if (Model.carf_type == "BATCH CARF")
{
#Html.Partial("Batch_Requestor1", new {id= Model.carf_id })
}else{
<h4><span class ="label label-success">#Html.DisplayFor(model=>model.created_by)</span></h4>
}
</div>
COntroller:
public ActionResult Batch_Requestor1(int id = 0)
{
var data = db.Batch_CARF.Where(x => x.carf_id == id && x.active_flag == true).ToList();
return PartialView(data);
}
Batch_Requestor1.cshtml
#model IEnumerable<PETC_CARF.Models.Batch_CARF>
#{
ViewBag.Title = "All Requestors";
}
<br/><br/>
<table class="table table-hover">
<tr class="success">
<th>
#Html.DisplayName("Full Name")
</th>
<th>
#Html.DisplayName("Email Add")
</th>
<th>
#Html.DisplayName("User ID")
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.fname) - #Html.DisplayFor(modelItem => item.lname)
</td>
<td>
#Html.DisplayFor(modelItem => item.email_add)
</td>
<td>
#Html.DisplayFor(modelItem => item.user_id)
</td>
</tr>
}
</table>
When I run this, I've got this error
The model item passed into the dictionary is of type '<>f__AnonymousType01[System.Int32]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[PETC_CARF.Models.Batch_CARF]'.
Any ideas how will I insert another partial view?

#Html.Partial() renders a partial view. It does not call an action method that in turn renders the partial. In your case
#Html.Partial("Batch_Requestor1", new {id= Model.carf_id })
is rendering a partial view named Batch_Requestor1.cshtml and passing it a model defined by new {id= Model.carf_id } (and anonymous object) but that view expects a model which is IEnumerable<PETC_CARF.Models.Batch_CARF>.
Instead, you need to use
#Html.Action("Batch_Requestor1", new {id= Model.carf_id })
which calls the method public ActionResult Batch_Requestor1(int id = 0) and passes it the value of Model.carf_id, which will in turn render the partial view.

Related

Update Partial view MVC4

I have this controller:
public ActionResult PopulateTreeViewModel()
{
MainModelPopulate mainModelPopulate = new MainModelPopulate();
// populate model
return View(mainModelPopulate);
}
That has a view like this:
#model xxx.xxx.MainModelPopulate
<table>
#foreach (var item2 in Model.CountryList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item2.CountryName);
</td>
</tr>
foreach (var item3 in item2.BrandList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item3.BrandName);
</td>
</tr>
foreach (var item4 in item3.ProductList)
{
<tr>
<td>
#Html.ActionLink(item4.ProductName, "FunctionX", new { idLab = item3.BrandID, idDep = item4.ProductID });
</td>
</tr>
}
}
}
</table>
The FunctionX controller is like this :
public ActionResult FunctionX(int idBrand=1 , int idProd=1)
{
List<ListTypeModel> typeModelList = new List<ListTypeModel>();
// populate typeModelList
return PartialView(typeModelList);
}
}
with this partial view:
#model IEnumerable<TControl.Models.ListTypeModel>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
I want to add this partial view in my main view (PopulateTreeViewModel) and update the table with the relative type of product contained in Function X.
I tried also to substitute #Html.ActionLink with #Ajax.ActionLink and it performs the same way.
Have you tried #Html.RenderAction(item4.ProductName, "FunctionX", new { idLab = item3.BrandID, idDep = item4.ProductID });
There are other options too..! Pls refer http://www.dotnet-tricks.com/Tutorial/mvc/Q8V2130113-RenderPartial-vs-RenderAction-vs-Partial-vs-Action-in-MVC-Razor.html

Fetch id for viewpage

FIXED
what i want to do is a viewpage that contains accountslist by clicking on any of account name it should open selected accountid Payablerecords and Reciveablerecords. Note:Payables and Receivables are two Propertiest Taken From same DataModel tbl_Transaction(Which is collection).So can i get Id for collections?
I am getting the Selected AccountID records in Payable view but I cant get the same id related record in Reciveable view plz help me out.
Here is the code.
public class AccountsController : Controller
{
private AccountBs objBs;
public AccountsController()
{
objBs = new AccountBs();
}
// GET: Shinwari/Accounts
public ActionResult Index()
{
var accounts = objBs.GetALL();
return View(accounts);
}
<%=#model IEnumerable<BOL.tbl_Accounts>
#{
ViewBag.Title = "Index";
}
<h2>Accounts</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Contact)
</th>
<th>
#Html.DisplayNameFor(model => model.Discription)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink(item.Name, "Index", "AccountDetailPayable", new {accountid=item.AId },null)
#*#Html.DisplayFor(modelItem => item.Name)*#
</td>
<td>
#Html.DisplayFor(modelItem => item.Contact)
</td>
<td>
#Html.DisplayFor(modelItem => item.Discription)
</td>
}
</table>%>
ReciveableAndPayablecontroller
private TransictionBs objbs;
public Details()
{
objbs = new TransictionBs();
}
// GET: Shinwari/AccountDetails
[HttpGet]
public ActionResult Index(int accountid)
{
ADetailsVm v = new ADetailsVm();
//Load both the collection properties
v.Payables = objbs.GetALL().Where(p => p.AId == accountid && p.tbl_TransictionType.Type.Contains("Payable")).ToList();
v.Reciveables = objbs.GetALL().Where(r => r.AId==accountid && r.tbl_TransictionType.Type.Contains("Reciveable")).ToList();
return View(v);
Veiw
#model BOL1.ADetailsVm
#{
ViewBag.Title = "Index";
}
<h2>AccountDetails</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table id="Payables" class="table">
<tr>
<th>
Date
</th>
<th>
Discription
</th>
<th>
Amount
</th>
</tr>
#foreach (var item in Model.Payables)
{
<tr>
<td>
#item.Date
</td>
<td>
#item.TDiscription
</td>
<td>
#item.Amount
</td>
</tr>
}
</table>
**Note Payable and reciveable both views are identical **
TO have same table work like 2 different properties you need to create new model class, In my case it is as following..
public ADetailsVm
{
List<tbl_Transiction>Payables{get;set;}
List<tbl_Transiction>Reciveables{get;set;}
}
And then add the following class to DBContext Class ... it would be like
public DbSet<ADetailsVm>ADetailsVm{get;set;}
You have to create new class where you need to add two lists as following.
public NewClass
{
List<tbl_Transiction>Payables{get;set;}
List<tbl_Transiction>Reciveables{get;set;}
}
and Add the class to your DbContext Class as follows.
public DbSet<NewClass>PayablesAndReceiveables{get;set;}
And loop your newly created lists objects in View where you need them.

System.InvalidOperationException: The partial view '_Reservaion' was not found or no view engine supports the searched locations

In my MVC 4 App i'm trying to use an Ajax form to implement a search to my 'Reservation' repository.
My View: (Views/Reservation/Index):
#model IEnumerable<RentalsForceProject.Models.Reservation>
#{
ViewBag.Title = "Reservations Center";
ViewBag.current = "Reservation";
}
#section featured {
#Html.Partial("_Navigator")
}
#using (Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ReservaionList"
}))
{
<input type="search" name="searchTerm" />
<input type="submit" name="Search By Contact" />
}
<p>
<input type="button" value="Create New" class="greenButton" style="margin-top:20px;" onclick="location.href='#Url.Action("Create", "Reservation")'"/>
</p>
#Html.Partial("_Reservation", Model)
My Partial view (Views/Reservation/_Reservation):
#model IEnumerable<RentalsForceProject.Models.Reservation>
<div id="ReservaionList" class="table-responsive">
<table class="table table-ordered">
<tr>
<th>
Reservation
</th>
<th>
Name
</th>
<th>
Dates
</th>
<th>
# Nights
</th>
<th>
Status
</th>
<th></th>
</tr>
#foreach (var res in Model)
{
<tr>
<td>
#res.ID
</td>
<td>
#if (res.Contact != null) {
#Html.ActionLink(res.Contact.FirstName + " " + res.Contact.LastName, "Details", "Contact", new { id=res.Contact.ID }, null)
//#res.Contact.LastName #: #res.Contact.LastName
}
</td>
<td>
#if (res.Request != null) {
#res.Request.StartDate #:- #res.Request.EndDate
}
</td>
<td>
#res.calculteNights()
</td>
<td>
#if (res.Status != null) {
#res.Status
}
</td>
<td>#Ajax.ActionLink("Edit", "Edit", "Reservation", new { id = res.ID }, new AjaxOptions() { HttpMethod = "Post" }) | #Ajax.ActionLink("View", "Details", new { id = res.ID }, new AjaxOptions() { HttpMethod = "Post" }) | #Ajax.ActionLink("Delete", "Delete", new { id = res.ID }, new AjaxOptions() { HttpMethod = "Post" })</td>
</tr>
}
</table>
</div>
My Index ActionResult:
public ActionResult Index(string searchTerm = null)
{
if (unitOfWork.currentClient == null)
{
return RedirectToAction("LogOn", "Account");
}
else
{
ViewBag.currentClient = unitOfWork.currentClient;
if (Request.IsAjaxRequest() && searchTerm != null)
return PartialView("_Reservaion", unitOfWork.currentClient.getAllReservationsBySearchTerm(searchTerm));
return View(unitOfWork.currentClient.getAllReservations());
}
}
When i lunch the 'search' button i can see it creates to nesessary model to the partial view, but nothing happens in the view.
I tried to use Chrome developers tools -> F12 - Network tab, and found out this exception:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The partial view '_Reservaion' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Reservation/_Reservaion.aspx
~/Views/Reservation/_Reservaion.ascx
~/Views/Shared/_Reservaion.aspx
~/Views/Shared/_Reservaion.ascx
~/Views/Reservation/_Reservaion.cshtml
~/Views/Reservation/_Reservaion.vbhtml
~/Views/Shared/_Reservaion.cshtml
~/Views/Shared/_Reservaion.vbhtml
Any Idea ?

MVC 4 - Return error message from Controller - Show in View

I am doing a C# project using Razor in VS2010 (MVC 4).
I need to return an error message from Controller to View and show it to the user.
What I have tried:
CONTROLLER:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
model.error_msg = model.update_content(model);
ModelState.AddModelError("error", "adfdghdghgdhgdhdgda");
ViewBag.error = TempData["error"];
return RedirectToAction("Form_edit", "Form");
}
VIEW:
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.ValidationSummary("error")
#Html.ValidationMessage("error")
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Please help me to achieve this.
The Return View(model) returns you error because you don't fill the model with the values in your post method and the model data for the dropdown is empty. Please provide the Get method to explain further how to manage displaying the error. In order to the error to be shown you should use this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
if(ModelState.IsValid())
{
--- operations
return Redirect("OtherAction", "SomeController");
}
// here you can use a little trick
//fill the model property that holds the information for the dropdown with the data
// you haven't provided the get method but it should look something like this
model.Countries = ... some data goes here;
model.dd_value = ... some other data;
model.dd_text = ... other data;
ModelState.AddModelError("", "adfdghdghgdhgdhdgda");
return View(model);
}
and then in the view just use :
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.ValidationSummary(true)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
This should work okay.
If you just use RedirectToAction it will redirect you to the get method --> you will have no error but the view will be just reloaded and no error would be shown.
other way around is that you can pass the error not by ModelState.AddError, but with ViewData["error"] like this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
TempData["error"] = "someErrorMessage";
return RedirectToAction("form_Post", "Form");
}
[HttpGet]
public ActionResult form_edit()
{
do stuff here ----
ViewData["error"] = TempData["error"];
return View();
}
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
<div>#ViewData["error"]</div>
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Thanks for all the replies.
I was able to solve this by doing the following:
CONTROLLER:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
model.error_msg = model.update_content(model);
return RedirectToAction("Form_edit", "Form", model);
}
public ActionResult form_edit(FormModels model, string searchString,string id)
{
string test = model.selectedvalue;
var bal = new FormModels();
bal.Countries = bal.get_contentdetails(searchString);
bal.selectedvalue = id;
bal.dd_text = "content_name";
bal.dd_value = "content_id";
test = model.error_msg;
ViewBag.head = "Heading";
if (model.error_msg != null)
{
ModelState.AddModelError("error_msg", test);
}
model.error_msg = "";
return View(bal);
}
VIEW:
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#ViewBag.error
#Html.ValidationMessage("error_msg")
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
}
If you want to do a redirect, you can either:
ViewBag.Error = "error message";
or
TempData["Error"] = "error message";
You can add this to your _Layout.cshtml:
#using MyProj.ViewModels;
...
#if (TempData["UserMessage"] != null)
{
var message = (MessageViewModel)TempData["UserMessage"];
<div class="alert #message.CssClassName" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>#message.Title</strong>
#message.Message
</div>
}
Then if you want to throw an error message in your controller:
TempData["UserMessage"] = new MessageViewModel() { CssClassName = "alert-danger alert-dismissible", Title = "Error", Message = "This is an error message" };
MessageViewModel.cs:
public class MessageViewModel
{
public string CssClassName { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
Note: Using Bootstrap 4 classes.

Retaining Form Values After Post (not part of model)

I have a MVC4 page that has a form with a collection of checkboxes, radio buttons and textboxes used as the search fields. Upon post the selections are parsed and the lower results grid is updated with new results. Right now all the form values are wiped out upon return and the new results are displayed in the grid - only the grid is part of the model.
I want all the form selections to retain their values after post so the user can see (and change) the selections for next post/search. The form is popuplated with viewbags.
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "searchform" }))
{
#Html.ValidationSummary("Please correct the following errors")
<div style="float:left;">
<div style="float:left;">
<label>Name:</label>
#Html.TextBox("name")
</div>
<div style="float:left; margin-left:15px">
<label>Company:</label>
#Html.TextBox("company")
</div>
<div style="float:left; margin-left:65px">
<label>Date Range:</label>
#Html.TextBox("dateStart", "", new { #class = "datefield", type = "date" })
to
#Html.TextBox("dateEnd", "", new { #class = "datefield", type = "date" })
</div>
</div>
<div style="clear: both;">
Match Any Categories? <input type="radio" name="categoryMatchAll" value="false" checked="checked" />
Match All Categories? <input type="radio" name="categoryMatchAll" value="true" />
</div>
<div style="float:left;">
<div id="searchform-categories" style="float:left;">
<div class="scroll_checkboxes">
<label>Categories</label>
<ul>
#foreach (var x in ViewBag.Categories)
{
<li>
<input type="checkbox" name="categories" value="#x.Id"/>
#x.Name
</li>
}
</ul>
</div>
</div>
<div id="searchform-diversity" style="float:left; margin-left:30px">
<div class="search-selection" style="float:left;">
<label>Minority Owned</label>
<ul>
#foreach (var x in ViewBag.Minorities)
{
<li>
#Html.RadioButton("minorities", (String)x.Id.ToString())
#x.Name
</li>
}
</ul>
</div>
<div class="search-selection" style="float:left;">
<label>Diversity Class</label>
<ul>
#foreach (var x in ViewBag.Classifications)
{
<li>
#Html.RadioButton("classifications", (String)x.Id.ToString())
#x.Name
</li>
}
</ul>
</div>
</div>
</div>
<div style="clear: both;">
<input type="submit" value="Search Profiles" />
<input type="submit" value="Reset" />
</div>
}
the data grid is bound to the model as
#model IEnumerable<VendorProfileIntranet.Models.VendorProfile>
<table id="VendorTable" width="100%" class="gradeA">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.CompanyName)
</th>
<th>
#Html.DisplayNameFor(model => model.City)
</th>
<th>
#Html.DisplayNameFor(model => model.State)
</th>
<th>
#Html.DisplayNameFor(model => model.DateCreated)
</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td class="list-field">
#Html.DisplayFor(modelItem => item.Name)
</td>
<td class="list-field">
#Html.DisplayFor(modelItem => item.CompanyName)
</td>
<td class="list-field">
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td class="list-field">
#Html.DisplayFor(modelItem => item.DateCreated)
</td>
<td class="list-field">
#Html.ActionLink("Edit", "Edit", new { id = item.ProfileID }) |
#Html.ActionLink("View", "View", new { id = item.ProfileID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ProfileID }, new { onclick = " return DeleteConfirm()" })
</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td> </td>
</tr>
</tfoot>
if you are using html in mvc then check solution 2 from here, value="#Request["txtNumber1"]" worked fine for me,
<input type="text" id="txtNumber1" name="txtNumber1" value="#Request["txtNumber1"]"/>
hope helps someone.
So here is how I typically solve this problem. My notes are purely my opinion (religous?) about naming classes in an MVC project to keep clear their purpose.
Couple of interfaces to keep it extensible:
// be specific about what type of results, both in the name of the
// interface and the property needed, you don't want to have overlapping
// properies on your classes, I like suffixing interfaces that are specific
// to a View or Partial View with View
public interface IPersonSearchResultsView
{
IEnumerable<EFPerson> PersonSearchResults { get; }
}
public interface IPersonSearchCriteriaView
{
PersonSearchCriteriaModel PersonSearchModel { get; }
}
Couple of classes
// I like suffixing classes that I only use for MVC with Model
public PersonSearchCriteriaModel
{
public string Name {get; set;}
public string Company {get; set;}
public string DateStart {get; set;}
public string DateEnd {get; set;}
}
// I like suffixing classes that I used passed to a View/Partial View
// with ViewModel
public class PersonSearchViewModel : IPersonSearchResultsView,
IPersonSearchCriteriaView
{
public IEnumerable<EFPerson> PersonSearchResults { get; set; }
public PersonSearchCriteriaModel PersonSearchModel { get; set; }
}
Now for your controllers, I'll set them up in a way that would also allow you to do Ajax in the future.
public PersonController : Controller
{
public ActionResult Search()
{
var model = new PersonSearchViewModel();
// make sure we don't get a null reference exceptions
model.PersonSearchModel = new PersonSearchCriteriaModel ();
model.PersonSearchResults = new List<EFPerson>();
return this.View(model);
}
[HttpPost]
public ActionResult Search(PersonSearchViewModel model)
{
model.PersonSearchResults = this.GetPersonResults(model.PersonSearchModel);
return this.View(model)
}
// You could use this for Ajax
public ActionResult Results(PersonSearchViewModel model)
{
model.PersonSearchResults = this.GetPersonResults(model.PersonSearchModel);
return this.Partial("Partial-SearchResults", model)
}
private GetPersonResults(PersonSearchCriteriaModel criteria)
{
return DbContext.GetPersonResults(criteria)
}
}
Create a couple of partial-views your Views.
/Views/Person/Partial-SearchCriteria.cshtml
#model IPersonSearchCriteriaView
// the new part is for htmlAttributes, used by Ajax later
#using (Html.BeginForm(..., new { id="searchCriteria" }))
{
// Here is were the magic is, if you use the #Html.*For(m=>)
// Methods, they will create names that match the model
// and you can back back to the same model on Get/Post
<label>Name:</label>
#Html.TextBoxFor(m => Model.PersonSearchModel.Name)
// or let mvc create a working label automagically
#Html.EditorFor(m => Model.PersonSearchModel.Name)
// or let mvc create the entire form..
#Html.EditorFor(m => Model.PersonSearchModel)
}
/Views/Person/Partial-SearchResults.cshtml
#model IPersonSearchResultsView
#foreach (var person in Model.PersonSearchResults )
{
<tr>
<td class="list-field">
#Html.DisplayFor(modelItem => person.Name)
</td>
// etc
</tr>
}
And Finally the view:
/Views/Person/Search.cshtml
#model PersonSearchViewModel
#Html.Partial("Partial-SearchCriteria", Model)
// easily change the order of these
<div id="searchResults">
#Html.Partial("Partial-SearchResults", Model);
</div>
Now enabling Ajax is pretty crazy easy (simplified and my not be exactly right):
$.Ajax({
url: '/Person/Results',
data: $('#searchCriteria').serialize(),
success: function(jsonResult)
{
$('#searchResults').innerHtml(jsonResult);
});
What I typically do is pass the posted Model back into the view. This way the values are not cleared out.
Your code would look something like this:
<div style="float:left;">
<div style="float:left;">
<label>Name:</label>
#Html.TextBox("name", Model.Name)
</div>
<div style="float:left; margin-left:15px">
<label>Company:</label>
#Html.TextBox("company", Model.Company)
</div>
<div style="float:left; margin-left:65px">
<label>Date Range:</label>
#Html.TextBox("dateStart", Model.DateStart, new { #class = "datefield", type = "date" })
to
#Html.TextBox("dateEnd", Model.DateEnd, new { #class = "datefield", type = "date" })
</div>
When initially getting the form, you'll have to create a new Model, otherwise the Model will be null and throw an exception when properties are called on it.
Sample Model
public class SearchModel
{
public SearchModel()
{
Results = new List<Result>();
}
public string Name {get; set;}
public string Company {get; set;}
public string DateStart {get; set;}
public string DateEnd {get; set;}
public List<Result> Results {get; set;}
}
#foreach (var item in Model.Results)
{
<tr>
<td class="list-field">
#Html.DisplayFor(modelItem => item.Name)
</td>
<td class="list-field">
#Html.DisplayFor(modelItem => item.CompanyName)
</td>
<td class="list-field">
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td class="list-field">
#Html.DisplayFor(modelItem => item.DateCreated)
</td>
<td class="list-field">
#Html.ActionLink("Edit", "Edit", new { id = item.ProfileID }) |
#Html.ActionLink("View", "View", new { id = item.ProfileID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ProfileID }, new { onclick = " return DeleteConfirm()" })
</td>
</tr>
}
Here is a link on creating models for a view in MVC.