How do I include html in C# block and C# in html block in the following View? - asp.net-mvc-4

I have my view here and it throws errors, either there is missing {} block or an "eternal components throws and exception" when I remove those if/else block along with #: the code works just like before so how do I include html code in a C# block and C# code in html block in the following view:
#model IEnumerable<ecomm2.Models.HomeSearchResultsViewModel>
#{
if (Model.Count < 1)
{
#:<p style="color:red">Item not found</p>
}
else
{
#:<table style="background-color:#f7f7f7;width:100%; border:0px solid black;">
foreach (var item in Model) {
#:<tr style="border:1px solid #bbb9b9;">
#: <td style="width:177px;">
#: <img src="~/Content/images/meter.jpeg" alt="Alternate Text" style="height:177px;width:177px;padding:10px;"/>
#:</td>
#:<td style="width:100%;padding-left:2px;float:left;padding-top:20px;border:0px solid black;font-size:medium">
<span>
#Html.ActionLink(item.ProductLineName, "GetProductDetails", "Product", new { id = item.Id }, new { }) <br />
#: </span>
#:<span style="font-size:small">By #Html.ActionLink(item.BrandName, "GetProductByBrandName", new { id=item.BrandName})</span><br />
#:<span style="font-size:x-small">
#Html.ActionLink(item.CategoryName, "GetProductsByCategoryName", new { id=item.CategoryName}) | Stock Count: #Html.DisplayFor(modelItem => item.StockCount)
</span><br />
#using(Html.BeginForm("AddToCart", "Cart", new { id=item.Id}))
{
<fieldset>
<input type="submit" name="name" value="Add to Cart" class="btn btn-default"/>
</fieldset>
}
</td>
<td style="width:20%;color:#00b02f;font-weight:bold;padding-top:20px;float:none;padding-left:20px;">
LKR: #Html.DisplayFor(modelItem => item.ListPrice)
</td>
</tr>
}
#:</table>
}
}
Here is the original code that threw the error
External component has thrown an exception.
Here is the original code
#model IEnumerable<ecomm2.Models.HomeSearchResultsViewModel>
#if (Model.Count < 1)
{
<p style="color:red">Item not found</p>
}
else
{
<table style="background-color:#f7f7f7;width:100%; border:0px solid black;">
#foreach (var item in Model) {
<tr style="border:1px solid #bbb9b9;">
<td style="width:177px;">
<img src="~/Content/images/meter.jpeg" alt="Alternate Text" style="height:177px;width:177px;padding:10px;"/>
</td>
<td style="width:100%;padding-left:2px;float:left;padding-top:20px;border:0px solid black;font-size:medium">
<span>
#Html.ActionLink(item.ProductLineName, "GetProductDetails", "Product", new { id = item.Id }, new { }) <br />
</span>
<span style="font-size:small">By #Html.ActionLink(item.BrandName, "GetProductByBrandName", new { id=item.BrandName})</span><br />
<span style="font-size:x-small">
#Html.ActionLink(item.CategoryName, "GetProductsByCategoryName", new { id=item.CategoryName}) | Stock Count: #Html.DisplayFor(modelItem => item.StockCount)
</span><br />
#using(Html.BeginForm("AddToCart", "Cart", new { id=item.Id}))
{
<fieldset>
<input type="submit" name="name" value="Add to Cart" class="btn btn-default"/>
</fieldset>
}
</td>
<td style="width:20%;color:#00b02f;font-weight:bold;padding-top:20px;float:none;padding-left:20px;">
LKR: #Html.DisplayFor(modelItem => item.ListPrice)
</td>
</tr>
}
</table>
}
In the Index view it calls the partial page "_SearchResultList" here is the video that shows all

None of your #: code is necessary. The reason you get the exception is that IEnumerable<T> does not have a property Count so your if block throws an exception. Change you code to
if (Model.Count() < 1)
of better, use
if (Model.Any())
and swap the code in the if and else blocks

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.

How do you open a kendo drop down popup on page load?

I have several uses for kendo drop-downs in my application (DDL, ComboBox, etc.).
I want them to open up on page load, but Kendo's documentation doesn't indicate that is possible.
I am using the MVC server variables.
This is my view coding:
<script id="itemTemplate" type="text/x-kendo-template">
# var index=FullName.indexOf(" *****");
if (index > 0)
{
#
<span style="font-weight:bold;">
#: FullName.substring(0, index)#
</span>
#
} else {
#
<span style="font-weight:normal;">
#: FullName#
</span>
#
}
#
</script>
<table class="form-horizontal table-condensed" style="width:100%;">
<tr style="height:400px;">
<td style="width:40%;vertical-align:top;">
<h4 style="width:100%;text-align:center;">Available Members</h4>
<h4 style="width:100%;text-align:center;font-size:smaller;">Current Cancer Center Members are highlighted in Bold.</h4>
#(Html.Kendo()
.MultiSelect()
.Name("AvailableWGMembers")
.DataTextField("FullName")
.DataValueField("id")
.ItemTemplateId("itemTemplate")
.TagTemplateId("itemTemplate")
.BindTo((System.Collections.IEnumerable)ViewBag.AvailableWGMembers)
.AutoBind(true)
.Placeholder("Click here to select one or more members to add, ...")
.AutoClose(false)
.HtmlAttributes(new { style = "width:100%;", #class = "Roles" })
.Events(events => { events.Change("doRoles");})
.Value(new int[0])
.Height(650)
)
</td>
<td style="width:20%;text-align:center;vertical-align:top;">
<input id="btnAdd" type="submit" value="Select" class="btn btn-default" disabled="disabled" />
</td>
<td style="width:40%;vertical-align:top;">
<h4 style="width:100%;text-align:center;">#Model.WGTitle</h4>
<h4 style="width:100%;text-align:center;font-size:smaller;">Current Cancer Center Members are highlighted in Bold.</h4>
#(Html.Kendo()
.MultiSelect()
.Name("ExistingWGMembers")
.AutoBind(false)
.DataTextField("FullName")
.DataValueField("id")
.ItemTemplateId("itemTemplate")
.TagTemplateId("itemTemplate")
.BindTo((System.Collections.IEnumerable)ViewBag.ExistingWGMembers)
.Placeholder("Click here to select one or more members to remove, ...")
.AutoClose(true)
.HtmlAttributes(new { style = "width:100%;", #class = "UnusedRoles" })
.Events(events => { events.Change("doRoles"); })
.Value(new int[0])
.Height(650)
)
</td>
</tr>
</table>
I want the lists to both be open when the page loads, and I want to be able to use unobstrusive jQuery or javascript to control it if I have to.
Does anyone have any suggestions?
It took a little digging, but I finally figured out the answer. It was actually pretty simple.
The following should be added to the unobstrusive javascript code file:
function openPopup(e)
{
if (e.sender.list[0].childNodes['1'].childNodes['0'].childElementCount > 0) {
e.sender.popup.open();
}
}
You add the following code to your event listing:
.Events(events => { ...; events.DataBound("openPopup"); })
This can be done with any of the lists that have popups like Kendo DropDownList or ComboBox or MultiSelect.
I would check for the list length to make sure the list has members so you don't get an ugly empty list shown, but otherwise the result is actually pretty simple.
This answer is dependent upon the code example at: http://demos.telerik.com/aspnet-mvc/window/index
I took that example from the Index.cshtml version of their example and simply replaced the Content value of the # with your table template from the original question:
#(Html.Kendo().Window()
.Name("window")
.Title("Your modal popup with dropdown menus")
.Content(#<text>
<table class="form-horizontal table-condensed" style="width:100%;">
<tr style="height:400px;">
<td style="width:40%;vertical-align:top;">
<h4 style="width:100%;text-align:center;">Available Members</h4>
<h4 style="width:100%;text-align:center;font-size:smaller;">Current Cancer Center Members are highlighted in Bold.</h4>
#(Html.Kendo()
.MultiSelect()
.Name("AvailableWGMembers")
.DataTextField("FullName")
.DataValueField("id")
.ItemTemplateId("itemTemplate")
.TagTemplateId("itemTemplate")
.BindTo((System.Collections.IEnumerable)ViewBag.AvailableWGMembers)
.AutoBind(true)
.Placeholder("Click here to select one or more members to add, ...")
.AutoClose(false)
.HtmlAttributes(new { style = "width:100%;", #class = "Roles" })
.Events(events => { events.Change("doRoles");})
.Value(new int[0])
.Height(650)
)
</td>
<td style="width:20%;text-align:center;vertical-align:top;">
<input id="btnAdd" type="submit" value="Select" class="btn btn-default" disabled="disabled" />
</td>
<td style="width:40%;vertical-align:top;">
<h4 style="width:100%;text-align:center;">#Model.WGTitle</h4>
<h4 style="width:100%;text-align:center;font-size:smaller;">Current Cancer Center Members are highlighted in Bold.</h4>
#(Html.Kendo()
.MultiSelect()
.Name("ExistingWGMembers")
.AutoBind(false)
.DataTextField("FullName")
.DataValueField("id")
.ItemTemplateId("itemTemplate")
.TagTemplateId("itemTemplate")
.BindTo((System.Collections.IEnumerable)ViewBag.ExistingWGMembers)
.Placeholder("Click here to select one or more members to remove, ...")
.AutoClose(true)
.HtmlAttributes(new { style = "width:100%;", #class = "UnusedRoles" })
.Events(events => { events.Change("doRoles"); })
.Value(new int[0])
.Height(650)
)
</td>
</tr>
</table>
</text>)
.Draggable()
.Resizable()
.Width(600)
.Actions(actions => actions.Pin().Minimize().Maximize().Close())
.Events(ev => ev.Close("onClose"))
)
I hope this helps!

The Index view does not receive the list partial from the ajax call made from Searchbox partial?

i have the following partial view for the the _searchbox partial
#model ecomm2.Models.MainSearchBoxViewModel
<div id="search-box-wrapper" style="text-align:center">
<div id="search-box-div" style="display:inline-block">
#using (Ajax.BeginForm("GetResults", "Partials",
new AjaxOptions {
HttpMethod="get",
InsertionMode=InsertionMode.Replace,
OnSuccess="updateMainResultsDiv",
UpdateTargetId="divMainResultsList"}))
{
<table>
<tr>
<td>
<fieldset>
<label>Search: </label>
</fieldset>
</td>
<td>
<fieldset>
#Html.DropDownListFor(m => m.ProdCatId, Model.MainSearchDDLCollection, new { style="width:200px;"})
</fieldset>
</td>
<td> </td>
<td>
<fieldset>
<input type="text" name="SearchText" style="width:400px"/>
</fieldset>
</td>
<td> </td>
<td><input type="submit" value="Search" /></td>
</tr>
</table>
}
</div>
</div>
<br />
then i have added this _SearchBox partial view to the layout so each page gets a searchbox with a drown category list to filter the search.
note: _searchbox partial is called by Another action in the "Partials" controller and works fine.
the action method "GetResults" is in the "Partials" controller and this is the method that is called by ajax from _SearchBox partial
[AjaxOnly]
public ActionResult GetResults(int ProdCatId, string SearchText)
{
var Products = db.mt_Products
.Where(e => e.SearchString.Contains(SearchText) & e.ProdCatId == ProdCatId)
.Select(e => new HomeSearchResultsViewModel
{
Id=e.Id,
ProdCode=e.ProdCode.Trim(),
ProductLineName= e.mt_Brands.BrandName.Trim() +" "+ e.ProdName.Trim(),
ListPrice=e.ListPrice,
ProdImage=e.ProdImg,
StockCount=e.Stock,
BrandName=e.mt_Brands.BrandName.Trim(),
CategoryName=e.mt_ProductCategories.CatName.Trim()
}).ToList();
return PartialView("_SearchResults", Products);
}
then i have the following code in Index view of the Home controller
#model IEnumerable<ecomm2.Models.HomeSearchResultsViewModel>
#{
ViewBag.Title = "Index";
}
<h2>Welcome Admin,</h2>
<p>
</p>
<div id="divMainResultsList">
#Html.Partial("_SearchResultsList", Model)
</div>
<script type="text/javascript">
function updateMainResultsDiv() {
$('#divMainResultsList').html()
}
</script>
when i passed a value to the search box and performed a search, it showed that search values were received by the action method GetResults and LINQ generates results but result were not placed on div area. Is this div placed on right spot?
it seems a bit complicated to post all and here is the video

Razor Engine Issue in MVC4

When I declare a text box in view page the below error will appear
The type arguments for method 'System.Web.Mvc.Html.InputExtensions.TextBoxFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>,
System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>)'
cannot be inferred from the usage. Try specifying the type arguments
explicitly
even I included
<compilation debug="true" targetFramework="4.0">
<!-- ... -->
</compilation>
this in webconfig file
but the same error shows .
............
my code
#Html.TextBoxFor(x => x.Entity, new { #id = "Entityname" })
//..........
model
public string Entity { set; get; }
//.........
//..............
.cshtml page
#model BOSSNew.Models.NewQuantifierM
#{Layout = "../Shared/_Layout.cshtml";}
<div class="breadCrumbHolder">
#{Html.RenderAction("BreadCrumb", "Base", new { menulist = new string[] { "Quantifier", "New Quantifier" }, CurrentURL = new string[] { "#", "#" } });}
</div>
<div class="divContentPane">
<div class="contentPaneHead">
<span class="contentPaneTitle">Users Details </span>
</div>
<table class="ClsTable ClsPad0">
<tr class="even">
<th>#LabelHelper.GetLabel("THLentity", 3)
</th>
<td>
#Html.TextBoxFor(x => x.Entity, new { #id = "Entityname" })
<img title="" id="selectentit" style="margin: 5px" onclick="getentity('txtentity','optentity')"
alt="" src="../../../Name.Controls/Themes/Name-Theme/images/entity.png">
</td>
</tr>
</table>
</div>
//.............
Any idea ?
Any help will be appreciated
You haven't defined model for a view, so you can't use
x => x.Field
expression.
It should look more or less like that:
SomeView.cshtml
#model SomeModel
#{Layout = "../Shared/_Layout.cshtml";}
<div class="breadCrumbHolder">
#{Html.RenderAction("BreadCrumb", "Base", new { menulist = new string[] { "Quantifier", "New Quantifier" }, CurrentURL = new string[] { "#", "#" } });}
</div>
<div class="divContentPane">
<div class="contentPaneHead">
<span class="contentPaneTitle">Users Details </span>
</div>
<table class="ClsTable ClsPad0">
<tr class="even">
<th>#LabelHelper.GetLabel("THLentity", 3)
</th>
<td>
#Html.TextBoxFor(x => x.Entity, new { #id = "Entityname" })
<img title="" id="selectentit" style="margin: 5px" onclick="getentity('txtentity','optentity')"
alt="" src="../../../Name.Controls/Themes/Name-Theme/images/entity.png">
</td>
</tr>
</table>
</div>
SomeModel.cs
public class SomeModel
{
public string Entity { set; get; }
}
And finally in your action method...
public ActionResult SomeMethod()
{
var model = new SomeModel();
//here fill the entity field
return View(model);
}

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.