RadioButtonList Model Binding in Asp.Net MVC 4.0 - asp.net-mvc-4

I want to do model binding for my radio button group , the situation is like this :
whenever I want to check either USD or % radio buttons , in my controller I want to get the true or false value from chosen radio buttons when I press submit the form button, but it appears that View doesn't pass me any value since I set int properties for them in my model. I get all the values from the form except my radio buttons.
I would appreciate any help
#for (int i = 0; i < Model.LstOrderDetails.Count; i++)
{
<tr>
#if (!string.IsNullOrEmpty(Model.LstOrderDetails[i].OrderedDiscountAmount) &&
(!string.IsNullOrEmpty(Model.LstOrderDetails[i].OrderedDiscountPerc)))
{
if(decimal.Round(Convert.ToDecimal(Model.LstOrderDetails[i].OrderedDiscountAmount), 2, MidpointRounding.AwayFromZero) != 0M)
{
<td class="col-md-2 col-xs-2">
<table style="font-size: 11px;">
<tr>
<td>
USD
</td>
<td> #Html.RadioButton(Model.LstOrderDetails[i].OrderDetailID, Model.LstOrderDetails[i].IsDiscountAmnt, Convert.ToBoolean(Model.LstOrderDetails[i].IsDiscountAmnt))
</td>
<td rowspan="2">#Html.TextBoxFor(x => x.LstOrderDetails[i].OrderedDiscountAmount, new { #class = "form-control", placeholder = "Discount", style = "font-size: 12px;" })
</td>
</tr>
<tr>
<td>
%
</td>
<td>#Html.RadioButton(Model.LstOrderDetails[i].OrderDetailID,Model.LstOrderDetails[i].IsDiscountPerc, Convert.ToBoolean(Model.LstOrderDetails[i].IsDiscountPerc))
</td>
<td>
</td>
</tr>
</table>
</td>
}
else
{
if (decimal.Round(Convert.ToDecimal(Model.LstOrderDetails[i].OrderedDiscountPerc), 2, MidpointRounding.AwayFromZero) != 0M)
{
removeafterzero = Model.LstOrderDetails[i].OrderedDiscountPerc.Substring(0, Model.LstOrderDetails[i].OrderedDiscountPerc.LastIndexOf('.'));
<td class="col-md-2 col-xs-2">
<table style="font-size: 11px;">
<tr>
<td>
USD
</td>
<td> #Html.RadioButton(Model.LstOrderDetails[i].OrderDetailID, Model.LstOrderDetails[i].IsDiscountAmnt, Convert.ToBoolean(Model.LstOrderDetails[i].IsDiscountAmnt))
</td>
<td rowspan="2">#Html.TextBoxFor(x => removeafterzero, new { #class = "form-control", placeholder = "Discount", style = "font-size: 12px;" })
</td>
</tr>
<tr>
<td>
%
</td>
<td> #Html.RadioButton(Model.LstOrderDetails[i].OrderDetailID, Model.LstOrderDetails[i].IsDiscountPerc, Convert.ToBoolean(Model.LstOrderDetails[i].IsDiscountPerc))
</td>
<td>
</td>
</tr>
</table>
</td>
}
}
}
//Model Part
public class OrderDetail
{
.
.
.
public string OrderedDiscountAmount { get; set; }
public string OrderedDiscountPerc { get; set; }
public int IsDiscountPerc { get; set; }
public int IsDiscountAmnt { get; set; }
}

to tie a field to your model you need to use a "for" helper. try changing your radio button to
#Html.RadioButtonFor(x => x.LstOrderDetails[i].OrderDetailID, "Dollar")
#Html.RadioButtonFor(x => x.LstOrderDetails[i].OrderDetailID, "Percent")
since both are tied to the same field, that field will have the value of the selected radio button (Dollar or Percent in this example)

Related

Cannot bind source type Umbraco.Web.Models.RenderModel to model type Repower.Cms.Umbraco.Models.Test

First of all I am new to Umbraco so if you see some basic mistakes don't judge me.
So I am creating currently a Login form which he goes to the database (check Username and Password) and reads the value which he returns and let's him Cannot bind source type Umbraco.Web.Models.RenderModel to model type Repower.Cms.Umbraco.Models.Test.
This Is my HTML:
#inherits Umbraco.Web.Mvc.UmbracoViewPage<Repower.Cms.Umbraco.Models.Test>
#{
Layout = "Master.cshtml";
}
<style type="text/css">
.btnStyle {
border: thin solid #000000;
line-height: normal;
width: 80px;
}
</style>
#using (Html.BeginForm("Test", "MembersProtectedPage", FormMethod.Post))
{
<div class="fontStyle">
<center>
<table style="margin-top: 100px;margin-left:150px">
<tr style="height:30px">
<td align="right">
#Html.LabelFor(m => m.User)
</td>
<td style="width:200px" align="right">
#Html.TextBoxFor(m => m.User)
</td>
<td style="width:250px;color:Red" align="left">
#Html.ValidationMessageFor(m => m.User)
</td>
</tr>
<tr style="height:30px">
<td align="right">
#Html.LabelFor(m => m.Password)
</td>
<td align="right">
#Html.PasswordFor(m => m.Password)
</td>
<td style="width:250px;color:Red" align="left">
#Html.ValidationMessageFor(m => m.Password)
</td>
</tr>
<tr style="height:30px">
<td colspan="2" align="center">
<input type="submit" value="Sign In" class="btnStyle" />
</td>
</tr>
</table>
</center>
</div>
}
This is my Model:
public class Test : RenderModel
{
public Test() : this(new UmbracoHelper(UmbracoContext.Current).TypedContent(UmbracoContext.Current.PageId)) { }
public Test(IPublishedContent content, CultureInfo culture) : base(content, culture) { }
public Test(IPublishedContent content) : base(content) { }
string connString = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
SqlConnection conn;
SqlCommand sqlcomm;
public string User { get; set; }
public string Password { get; set; }
public bool IsUserExist(string emailid, string password)
{
bool flag = false;
conn = new SqlConnection(connString);
conn.Open();
sqlcomm = new SqlCommand();
sqlcomm.Connection = conn;
sqlcomm.CommandType = System.Data.CommandType.StoredProcedure;
sqlcomm.CommandText = "dbo.uspLogin";
sqlcomm.Parameters.AddWithValue("#pLoginName", User);
sqlcomm.Parameters.AddWithValue("#pPassword", Password);
SqlParameter retval = sqlcomm.Parameters.Add("#RESULT", SqlDbType.VarChar);
retval.Direction = ParameterDirection.ReturnValue;
sqlcomm.ExecuteNonQuery(); // MISSING
string retunvalue = (string)sqlcomm.Parameters["#RESULT"].Value;
switch (retunvalue)
{
case "0":
flag = true;
break;
case "1":
flag = false;
break;
case "2":
flag = false;
break;
default:
flag = false;
break;
}
return flag;
}
}
And this is my Controller:
public class TestController : Controller
{
public ViewResult Login()
{
return View();
}
[HttpPost, ValidateInput(false)]
public ActionResult Login(Test model)
{
if (ModelState.IsValid)
{
if (model.IsUserExist(model.User, model.Password))
{
ViewBag.UserName = model.User;
FormsAuthentication.RedirectFromLoginPage(model.User, false);
}
else
{
ModelState.AddModelError("", "Username or Password Incorrect.");
}
}
return View(model);
}
}
So I am inheriting a RenderModel because previously my error was "The model item passed into the dictionary is of type Repower.Cms.Umbraco.Models.Test', but this dictionary requires a model item of type 'Umbraco.Web.Models.RenderModel'."
So I changed it (searched a lot in the Internet) and now I get this error.
Is also the rest of the code correct? The way that I access the Database and everything? I am expecting a Return value from the Database (don't know if that is correct)
Could Someone please help me?
I need to get this done today.
Thanks in Advance
There's a few issues with your implementation.
Use the Umbraco MemberService
You're reinventing the wheel by building a new table which holds member information (such as username and password).
Umbraco has built in membership which can handle members of your site. You can view the GUI in Umbraco at /umbraco/#/member. Using this GUI, you can manually create and edit members.
You can also programmatically create end edit members in this section using this MemberService.
For example, register a member:
var MemberService = ApplicationContext.Current.Services.MemberService
var member = MemberService.CreateMemberWithIdentity(newEmail, newEmail, newName, "Member");
MemberService.Save(member);
MemberService.SavePassword(member, newPassword);
FormsAuthentication.SetAuthCookie(newEmail, true);
Login:
var memberService = ApplicationContext.Current.Services.MemberService;
if (memberService.Exists(email))
{
if (Membership.ValidateUser(email, password))
{
FormsAuthentication.SetAuthCookie(email, true);
}
}
You can read about what other methods are available here.
You're mixing up your MVC
Your Test model isn't purely a model, is also has some controller in it as it is handling database stuff too!
Ideally, your model should just contain the data which has been sent forward, and your TestController should handle using that data.
As for fixing your binding issue
You're currently setting your page view model to Repower.Cms.Umbraco.Models.Test, where as I think it should be left as is.
Stop this model from inheriting from RenderModel.
Instead, render a partial with your code.
For your page view:
#inherits Umbraco.Web.Mvc.UmbracoViewPage
#{
Layout = "Master.cshtml";
}
#Html.Partial("Login", new Repower.Cms.Umbraco.Models.Test())
Partial called Login.cshtml:
#model Repower.Cms.Umbraco.Models.Test
#using (Html.BeginUmbracoForm<TestController>("Login"))
{
<div class="fontStyle">
<center>
<table style="margin-top: 100px;margin-left:150px">
<tr style="height:30px">
<td align="right">
#Html.LabelFor(m => m.User)
</td>
<td style="width:200px" align="right">
#Html.TextBoxFor(m => m.User)
</td>
<td style="width:250px;color:Red" align="left">
#Html.ValidationMessageFor(m => m.User)
</td>
</tr>
<tr style="height:30px">
<td align="right">
#Html.LabelFor(m => m.Password)
</td>
<td align="right">
#Html.PasswordFor(m => m.Password)
</td>
<td style="width:250px;color:Red" align="left">
#Html.ValidationMessageFor(m => m.Password)
</td>
</tr>
<tr style="height:30px">
<td colspan="2" align="center">
<input type="submit" value="Sign In" class="btnStyle" />
</td>
</tr>
</table>
</center>
</div>
}
Finally, update your controller to inherit from SurfaceController.
I hope this helps
This isn't the complete solution but should help you get off on the right track.

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

Insert Partial View to a another Partial View

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.

Html.ActionLink object parameters + MVC4

I am calling Edit action from my view that should accept an object as parameter.
Action:
[HttpPost]
public ActionResult Edit(Organization obj)
{
//remove the lock since it is not required for inserts
if (ModelState.IsValid)
{
OrganizationRepo.Update(obj);
UnitOfWork.Save();
LockSvc.Unlock(obj);
return RedirectToAction("List");
}
else
{
return View();
}
}
From View:
#foreach (var item in Model) {
cap = item.GetValForProp<string>("Caption");
nameinuse = item.GetValForProp<string>("NameInUse");
desc = item.GetValForProp<string>("Description");
<tr>
<td class="txt">
<input type="text" name="Caption" class="txt" value="#cap"/>
</td>
<td>
<input type="text" name="NameInUse" class="txt" value="#nameinuse"/>
</td>
<td>
<input type="text" name="Description" class="txt" value="#desc"/>
</td>
<td>
#Html.ActionLink("Edit", "Edit", "Organization", new { obj = item as Organization }, null)
</td>
</tr>
}
It is raising an exception: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'PartyWeb.Controllers.Internal.OrganizationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Can somebody advise how to pass object as parameter?
Can somebody advise how to pass object as parameter?
Why are you using an ActionLink? An ActionLink sends a GET request, not POST. So don't expect your [HttpPost] action to ever be invoked by using an ActionLink. You will have to use an HTML form and include all the properties you want to be sent as input fields.
So:
<tr>
<td colspan="4">
#using (Html.BeginForm("Edit", "Organization", FormMethod.Post))
{
<table>
<tr>
#foreach (var item in Model)
{
<td class="txt">
#Html.TextBox("Caption", item.GetValForProp<string>("Caption"), new { #class = "txt" })
</td>
<td class="txt">
#Html.TextBox("NameInUse", item.GetValForProp<string>("NameInUse"), new { #class = "txt" })
</td>
<td class="txt">
#Html.TextBox("Description", item.GetValForProp<string>("Description"), new { #class = "txt" })
</td>
<td>
<button type="submit">Edit</button>
</td>
}
</tr>
</table>
}
</td>
</tr>
Also notice that I used a nested <table> because you cannot have a <form> inside a <tr> and some browser such as IE won't like it.

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.