Retaining Form Values After Post (not part of model) - asp.net-mvc-4

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.

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.

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);
}

Mvc 4 model binding not working dynamically added partial view

I am trying to create a form where in user can add controls. I have main view
#model MVCDynamicFormGenerator.Models.FormViewModel
#{
ViewBag.Title = "Create";
}
#using (#Html.BeginForm())
{
<fieldset>
#Html.HiddenFor(form => form.Form.Uid)
#Html.Hidden("ListFields", ViewData["ListFields"])
<p>
#Html.LabelFor(form => form.Form.FormName)
#Html.TextBoxFor(form => form.Form.FormName)
</p>
<div id="FormFieldList">
#foreach (var formfield in Model.FormFields)
{
switch (formfield.ControlType)
{
case ("Textbox"):
Html.RenderPartial("Textbox", formfield);
break;
}
}
</div>
<h4>
[+] Add a Field
</h4>
<div id="FieldType">
<table>
<tr>
<th>
Select a Field Type
</th>
</tr>
<tr>
<td>
#Html.DropDownList("FieldTypes", new SelectList(Model.FormFields[0].FormFieldTypes, "Value", "Text"), new { id = "SelectedFieldUid" })
#Html.ActionLink("Add Field", "NewFormField", new { formId = ViewContext.FormContext.FormId, selectedFieldType = "SelectedFieldUid" }, new { id = "newFormField" })
#Html.ValidationMessageFor(model => model.FormFields)
</td>
</tr>
</table>
</div>
<p>
<input type="submit" value="Create" />
<input type="button" value="Cancel" '#Url.Action("List")');" />
</p>
</fieldset>
}
On dropdown change I am loading a partial view which is working(User can add n number of times)
#model MVCDynamicFormGenerator.Models.FormFieldViewModel
<div class="FormField">
#using (#Html.BeginForm())
{
<table>
<tr>
<th>
Form Field
</th>
<th>
Field Type
</th>
</tr>
<tr>
<td style="width: 45%;">
#Html.TextBoxFor(formfield => formfield.FormFieldName)
#Html.ValidationMessageFor(formfield => formfield.FormFieldName)
</td>
<td style="width: 25%;">
#Html.DropDownListFor(formfield => formfield.SelectedFormFieldType,
new SelectList(Model.FormFieldTypes, "Value", "Text",
Model.SelectedFormFieldType),
new { disabled = "disabled" })
#Html.HiddenFor(formfield => formfield.SelectedFormFieldType)
#Html.ValidationMessageFor(formfield => formfield.SelectedFormFieldType)
</td>
</tr>
</table>
}
</div>
/// form models
public class FormViewModel
{
//Properties
public Form Form { get; set; }
public List<FormFieldViewModel> FormFields { get; set; }
//Constructor
public FormViewModel()
{
Form = new Form();
FormFields = new List<FormFieldViewModel>();
}
}
public class FormFieldViewModel
{
public string FormFieldName { get; set; }
public string SelectedFormFieldType { get; set; }
}
controller methods
[HttpPost]
public ActionResult Create(FormViewModel viewModel)
{
return View();
}
All the field information related to main view gets available but FormFieldViewModel list gives zero count
Any help or suggestion to fix this

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.

how to checked checkbox using view model

i try to make a simple project, that check the list of checkbox. my database is like this... !
i want to check my checkbox when hotel have the facilities...
i have code like this...
my controller
public ActionResult Facility()
{
var model = db.Facilities
.Where (htl => htl.FacilityID == hotelFacility.FacilityID)
.Select(htl => new CheckFacilityVM
{
FacilityID = htl.FacilityID,
facilityName = htl.FacilityName,
facilityAvailable = htl.IsActive == true,
})
.ToList();
return View(model);
}
my constuctor class
public Facility ShowRoomFacility(int HotelID)
{
var x = (from d in db.Facilities
where d.FacilityID == HotelID
select d).FirstOrDefault();
return x;
}
my view
#model List<XNet.WebUI.Hotel.ViewModel.CheckFacilityVM>
#{
ViewBag.Title = "Facility";
}
<h2>Facility</h2>
#using (Html.BeginForm())
{
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th> is available</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(x => x[i].FacilityID)
#Html.HiddenFor(x => x[i].FacilityID)
</td>
<td>
#Html.DisplayFor(x => x[i].facilityName)
#Html.HiddenFor(x => x[i].facilityName)
</td>
<td>
#Html.CheckBoxFor(x => x[i].facilityAvailable)
</td>
</tr>
}
</tbody>
</table>
}
<br />
<input style="width:100px;" type="button" title="Save" value="Save" onclick="location.href='#Url.Action("Index","Hotel")'" />
<input style="width:100px;" type="button" title="Reset" value="Reset" onclick="location.href='#Url.Action("Facility","Hotel")'" />
<input style="width:100px;" type="button" title="Cancel" value="Cancel" onclick="location.href='#Url.Action("Room","Hotel")'" />
how can i make checkbox is checked ??
help me please
You want to store the true/false in your database as a bit. 0 is false and 1 is true.
Then when you have a boolean property in your view model, populated by your database
public bool FacilityXAvailable { get; set; }
On your view you can then just do this
#Html.DisplayFor(model=>model.FacilityXAvailable)
That will display a checkbox checked on unchecked depending on Db value.