I am working in MVC 4 and totally new to it. I have two Partial views under shared folder and in index method I am using this code to show these partial views:
#Html.Partial("_Login")
#Html.Partial("_Register")
code of _Login partial view:
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<link href="~/Content/StyleSheet1.css" rel="stylesheet" />
#using (
Ajax.BeginForm(
"Index", "Partial" ,
new AjaxOptions()
{
UpdateTargetId="LoginClass",
HttpMethod="Post"
}
)
)
{
<div class="loginform">
#Html.Label("Name")
<div>#Html.TextBox("Name")</div>
#Html.Label("Password")
<div>#Html.TextBox("password")</div>
</div>
<div>
<input type="submit" value="submit" />
</div>
}
code of LoginClass:
namespace PartialViews.Models
{
public class LoginClass
{
[Required(ErrorMessage="Required")]
public string Name { get; set; }
[Required]
public string Password { get; set; }
}
}
Controller action for Login:
[HttpGet]
public ActionResult Index()
{
var lc = new LoginClass();
return View(lc);
}
[HttpPost]
public string Index(LoginClass lc)
{
return "Email: " + lc.Name + "</br>" +"Password:" + lc.Password;
}
But validations are not working! What I need to do to make validations work.
Need help, Thanks in advance.
Do something like this:
[HttpPost]
public string Index(LoginClass lc)
{
if(ModelState.IsValid)
{
return "Email: " + lc.Name + "</br>" +"Password:" + lc.Password;
}
else
{
return PartialView("yourview",lc);
}
}
and in view:
<div id="formContainer">
#using (
Ajax.BeginForm(
"Index", "Partial" ,
new AjaxOptions()
{
UpdateTargetId="LoginClass",
HttpMethod="Post",
InsertionMode = "Replace"
}
)
)
{
#Html.ValidationSummary(true)
<div class="loginform">
#Html.Label("Name")
<div>#Html.TextBoxFor(x=>x.Name)</div>
<div>#Html.ValidationMessageFor(x=>x.Name)</div>
#Html.Label("Password")
<div>#Html.TextBox(x=>x.password)</div>
<div>#Html.ValidationMessageFor(x-=>x.password)</div>
</div>
<div>
<input type="submit" value="submit" />
</div>
}
</div>
on top of view set model for view like this:
#model LoginClass
Update 2:
Create login form as partial view:
#using (
Ajax.BeginForm(
"Index", "Partial" ,
new AjaxOptions()
{
UpdateTargetId="formContainer",
HttpMethod="Post",
InsertionMode = "Replace"
}
)
)
{
#Html.ValidationSummary(true)
<div class="loginform">
#Html.Label("Name")
<div>#Html.TextBoxFor(x=>x.Name)</div>
<div>#Html.ValidationMessageFor(x=>x.Name)</div>
#Html.Label("Password")
<div>#Html.TextBox(x=>x.password)</div>
<div>#Html.ValidationMessageFor(x-=>x.password)</div>
</div>
<div>
<input type="submit" value="submit" />
</div>
}
Load it in main view inside container div:
<div id="formContainer">
// Load you login form here as partial view
</div>
Now your action:
[HttpPost]
public string Index(LoginClass lc)
{
if(ModelState.IsValid)
{
// do anything here if valid data
}
else
{
// data not valid
return PartialView("partialviewlogin",lc);
}
}
Related
I didn't understand how to send and save the selected languages.
When I use Plugin (select2), there is a problem with Js and other Plugin in the template.
View:
<div class="form-group">
<label class="col-md-4 control-label">Which Languages Speak *</label>
<span style="color:red;"><small> >>> You can select multiple languages.</small></span>
<div class="col-md-8 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon" style="max-width: 100%;"><i class="glyphicon glyphicon-list"></i></span>
<select class="form-control" name="Dil_Id[]" multiple="multiple" id="select" required>
#foreach (var item in dilList)
{
<option value="#item.Id">#item.DilAdi_Eng</option>
}
</select>
</div>
</div>
</div>
Controller:
public class YeniIhtiyacSahibiController : Controller
{
// GET: IhtiyacSahibi/YeniIhtiyacSahibi
IhtiyacSahibiUyeBLL _ISUye = new IhtiyacSahibiUyeBLL();
ISUDilBLL _isuDil = new ISUDilBLL(); // members languages
public ActionResult Index(int Id = 0)
{
var model = _ISUye.GetById(Id);
ViewBag.Mesaj = GenelAraclarBLL.KayitYeni(); // Message Succesfull
return View(model);
}
[HttpPost]
public ActionResult Index(IhtiyacSahibiUye model)
{
return View(model);
}
}
What can i do without plugin and how can i send and save that items? I don't know how to make and send the list. Thank you for your time.
I post forms with select2 like this:
$.ajax({
url: "/Projects/Edit/",
type: "POST",
data: {
__RequestVerificationToken: token,
ProjectManagersString: $("#ProjectManagers").val(), //select 2 control value
}
})
Controller:
public async Task<ActionResult> Edit(Project project)
{
if (Request.Form["ProjectManagersString[]"] != null)
{
foreach (var pmstring in Request.Form["ProjectManagersString[]"].Split(','))
{
}
}
}
The binding of the form controls is done in the parameter indicated in the Post method of the controller. Following an example to access the selected value.
The Model
public class Mymodel
{
public List<SelectListItem> dilList { get; set; }
public int? Id { get; set; }
}
The Controller
public class YeniIhtiyacSahibiController : Controller
{
[HttpGet]
public ActionResult Index()
{
//Get Method
return View(model);
}
[HttpPost]
public ActionResult Index(IhtiyacSahibiUye model)
{
car selectedId=model.Id
return View(model);
}
}
The View
#model namespace.Models.Mymodel
#{
Layout = null;
}
<html>
<head>
</head>
<body>
#using (Html.BeginForm("Index", "YeniIhtiyacSahibiController", FormMethod.Post))
{
<table>
<tr>
<td>
DilAdi_Eng:
</td>
<td>
#Html.DropDownListFor(m => m.Id, Model.dilList, "Language")
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
}
</body>
</html>
Cordialement
I have this code in my controller:
[HttpPost]
public ActionResult Index(double userLat, double userLng)
{
var context = new weddingspreeEntities();
var coordinates = context.Venues
.Select(loc => new { vname = loc.VenueName, lat = loc.VenueLat, lng = loc.VenueLong })
.ToList();
string venueName = string.Empty;
List<SearchModel.DistLocation> venDistList = new List<SearchModel.DistLocation>();
for (int i = 0; i < coordinates.Count; i++)
{
string name = coordinates[i].vname;
double? lat = coordinates[i].lat;
double? lng = coordinates[i].lng;
var loc1Lat = lat.Value;
var loc1Lng = lng.Value;
var loc2Lat = userLat;
var loc2Lng = userLng;
double distance = TrackingHelper.CalculateDistance(
new SearchModel.Location() { Latitude = loc1Lat, Longitude = loc1Lng },
new SearchModel.Location() { Latitude = loc2Lat, Longitude = loc2Lng });
//convert kilometers to miles
double distMiles = distance * 0.621371192;
venueName = name;
venDistList.Add(new SearchModel.DistLocation() { venName = name, Distance = distMiles });
}
return View(venDistList);
}
I have this code in my view:
<div class="row">
<div class="form-group">
<div class="col-md-6">
#using (Html.BeginForm("Search", "Home", FormMethod.Post))
{
#*#Html.TextBoxFor(model => model.cityName)*#
<label>Enter City and State or Zip Code</label>
<input type="text" id="citystate" name="citystate" />
<label>Enter Your Wedding Date</label>
<input class="datefield" data-val="true" data-val-required="Date is required" id="weddingDate" name="weddingDate" type="date" value="1/11/1989" />
<label>Enter Your Guest Count</label>
<input type="text" id="guestcount" name="guestcount" />
<input type="button" id="search" name="search" value="Search for Venues" />
}
</div>
<!--This is the div where the google map will render -->
<div class="col-md-6">
<div id="map_canvas" style="height: 600px;"></div>
</div>
</div>
</div>
<div>
#Html.Partial("_SearchResults")
</div>
I have omitted some of my view for brevity
This is the partial view I am trying to render:
#model IEnumerable<WeddingSpree_Alpha.Models.SearchModel.DistLocation>
#{
Layout = null;
}
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
foreach (var item in Model)
{
#item.venName
#item.Distance
}
}
What I am trying to do is to have the user enter the values in the search box and then after the click post the results (in the list named venDistList) to the view using a foreach statement.
The model looks like this:
public class SearchModel
{
public string cityName { get; set; }
public DateTime weddingDate { get; set; }
public int guestCount { get; set; }
public class Location
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public class DistLocation
{
public string venName { get; set; }
public double Distance { get; set; }
}
}
I would like the list results to populate after the button click (post) on the page. I thought my code would do that however. I get the following error:
System.NullReferenceException: 'Object reference not set to an instance of an object'
I know that error happens when you try to use a model that is not populated yet but I thought I did that in my controller code? What exactly could be throwing that error?
This is the controller code for my partial view:
public ActionResult _SearchResults(SearchModel model)
{
return View();
}
If you are not at least instantiating an instance of IEnumerable to pass back (even if it is empty) then it will throw the null reference when you try to iterate throught the model in the partial view.
Edit: (Code trimmed down for example) Your original error is that you are trying to iterate through an object that does not exist. The below will show you how to make user of an Ajax call on your form submit to dynamically generate your partial view and attach it to your main page
Controller:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult _SearchResults(string citystate, DateTime? weddingDate, double? guestcount)
{
List<SearchModel.DistLocation> venDistList = new List<SearchModel.DistLocation>();
venDistList.Add(new SearchModel.DistLocation() { venName = "weee1", Distance = 2 });
venDistList.Add(new SearchModel.DistLocation() { venName = "weee2", Distance = 4 });
venDistList.Add(new SearchModel.DistLocation() { venName = "weee3", Distance = 6 });
return PartialView(venDistList);
}
Index.cshtml:
#{
ViewBag.Title = "Home Page";
}
#*This is our form which will feed our user input and drive our search results output*#
<div class="row">
<div class="form-group">
<div class="col-md-6">
<form id="searchMe">
<label>Enter City and State or Zip Code</label>
<input type="text" id="citystate" name="citystate" />
<label>Enter Your Wedding Date</label>
<input class="datefield" data-val="true" data-val-required="Date is required" id="weddingDate" name="weddingDate" type="date" value="1/11/1989" />
<label>Enter Your Guest Count</label>
<input type="text" id="guestcount" name="guestcount" />
<button type="submit" class="btn btn-primary">Search for Venues</button>
</form>
</div>
</div>
</div>
<div class="row">
#*This is where we want our search results to appear when user hits submit on our form*#
<div id="SearchResult"></div>
</div>
#section scripts {
<script>
$(document).ready(function () {
//When the user hit the submit button we will post the form results to our partial view controller
$('#searchMe').submit(function () {
$.ajax({
method: "POST",
url: "/Home/_SearchResults",
data: $(this).serialize(),
success: function (result) {
//When then load our partial view into our containing div on the main page
$('#SearchResult').html(result);
}
});
return false;
});
});
</script>
}
Partial View (_SearchResult.cshtml)
#model IEnumerable<deletemeweb2.Models.SearchModel.DistLocation>
#{
Layout = null;
}
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Search Results</h3>
</div>
<div class="panel-body">
#if (Model != null || Model.Count() < 1)
{
using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
foreach (var item in Model)
{
<p>#item.venName</p>
<p>#item.Distance</p>
}
}
}
else
{
<p>No results found</p>
}
</div>
</div>
I am creating a login page:
When I go to the login page Login view should be rendered. on submit, http POST should be triggered which should render the home page with the username. My problem is that whatever I do it is the http GET method that is being called on submit. I am new to mvc ans wondering what I am doing wrong. Why is the program on calling http POST method not submit button click
// My login Class(I mean the model looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace a.Models
{
public class Login
{
public string username { get; set; }
public string password { get; set; }
}
}
// Controller looks like this:
namespace b.Controllers
{
public class LoginController : Controller
{
[HttpPost]
public ActionResult Login(Login Ls)
{
return View();
}
[HttpGet]
public ActionResult Login()
{
return View(new Login());
}
}
}
// Login view look like this
#model a.Models.Login
#{
ViewBag.Title = "Login Page";
}
<html>
<head>
<title>Login Here</title>
<link href="#Url.Content("~/Content/cssLogin.css")" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="bg">
<img src="~/Photos/login2.jpg" />
</div>
<form class="form-2">
<p class="float">
#*<label for="login"><i class="icon-user"></i>Username</label>
<input type="text" name="login" placeholder="Username or email">*#
#Html.LabelFor(model => model.username, new { #class = "icon-use" })
#Html.TextBoxFor(model => model.username, new { data_bind = "value: username" })
</p>
<p class="float">
#*<label for="password"><i class="icon-lock"></i>Password</label>
<input type="password" name="password" placeholder="Password" class="showpassword">*#
#Html.LabelFor(model => model.password, new { #class = "icon-lock" })
#Html.PasswordFor(m => m.password, new { data_bind = "value: password", placeholder = "Password" })
</p>
<p class="clearfix">
<input type="submit" value="Log in">
</p>
</form>
</body>
</html>
// Home View looks like this
#model a.Models.Login
#{
ViewBag.Title = "Home";
}
<h2>Home</h2>
<h2>This is University Home page</h2>
#Model.username
You may need to change the code line this:
public ActionResult Login()
{
return View(new Login());
}
And:
[HttpPost]
public ActionResult Login(Login Ls)
{
return View();
}
And nothing else...
I am new to asp .net mvc 4.0. i have given model. i am not getting how can i create view for model. I am facing problem at IList JournalEntries. other entry i am able to do.
public class Journal : BaseClass
{
public virtual string VoucherNo { get; set; }
public virtual DateTime VoucherDate { get; set; }
public string VoucherDateView {
get
{
return VoucherDate.ToShortDateString();
}
}
public IList<JournalEntry> JournalEntries { get; set; }
public IList<Ledger> Accounts { get; set; }
public double TotalAmount
{
get
{
double sum = 0;
if (JournalEntries != null && JournalEntries.Count>0)
foreach (var journal in JournalEntries)
sum = journal.Principal + journal.Interest+sum;
return sum;
}
}
}
I have tried below view but add entry doesn't works.
#model Sms.CoreSociety.Journal
#{
ViewBag.Title = "Create";
}
#{
string data = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);
}
<script type="text/javascript">
$(document).ready(function () {
$('#document').validate();
$("#VoucherDate").mask("99/99/9999", { placeholder: " " });
function entryVm(entries) {
var self = this;
self.entryList = ko.observableArray(entries);
self.entry = ko.observable();
self.rowClick = function(entry1) {
alert("Delete alert");
self.dispatchList.remove(entry1);
};
self.addEntry = function() {
alert("Add alert");
this.entryList.push({ AccountName_AccountHead: "", DebitCredit: "", Principal: "0.0", Interest: "0.0", Narration: ""});
};
}
var models = #Html.Raw(Json.Encode(Model.JournalEntries)) ;
ko.applyBindings(new entryVm(models));
});
</script>
#using (Html.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object>() { { "class", "form-horizontal" }, { "id", "document" } }))
{
#Html.ValidationSummary(true)
<fieldset>
<div class="row">
<div class="span1">
<label>Voucher No</label>
</div>
<div class="span5">
#Html.DisplayFor(model => model.VoucherNo)
</div>
</div>
<div class="row">
<div class="span1">
<label>Voucher Date</label>
</div>
<div class="span5">
#Html.TextBoxFor(model => model.VoucherDate, "{0:dd/MM/yyyy}", new Dictionary<string, object>() { { "class", "required" } })
</div>
</div>
<div class="row">
<div class="span1">
<label>Amount</label>
</div>
<div class="span5">
#Html.DisplayFor(model => model.TotalAmount)
</div>
</div>
<input type="submit" value="Save" class="btn" id="submit"/>
#if (Model.Id != new Guid())
{
<div style="float: right">
<a class="btn btn-danger" href='#Url.Action("Delete")/#Model.Id' aria-hidden="true">Delete</a>
</div>
}
</fieldset>
}
<h4>Journal Entry</h4>
<p >Entry for<span data-bind="text: entryList().length"> </span> entry(s)</p>
<button data-bind="click: addEntry" class="btn">Add Record</button>
<table>
<tbody data-bind="template: { name: 'entryRowTemplate', foreach: entryList }"></tbody>
</table>
<script type="text/html" id="entryRowTemplate">
<tr>
<td>AccountName_AccountHead: \$ <input data-bind="value: AccountName.AccountHead"/> </td>
<td>DebitCredit: \$ <input data-bind="value: DebitCredit"/></td>
<td>Principal: \$ <input data-bind="value: Principal"/></td>
<td>Interest: \$ <input data-bind="value: Interest"/></td>
<td>Narration: \$ <input data-bind="value: Narration"/></td>
<td>Delete</td>
</tr>
</script>
below is my Journal controller
using System;
using System.Linq;
using System.Web.Mvc;
using Sms.CoreSociety;
using System.Collections.Generic;
namespace SmsModernUI.Controllers
{
public class JournalController : BaseController
{
//
// GET: /AccountGroup/
public ActionResult Index()
{
var journals = Repository.GetAll<Journal>().OrderBy(x => x.VoucherNo);
return View(journals);
}
public ActionResult Create(Guid id)
{
if (id == new Guid())
{
var journal = new Journal();
string lastvoucherno = Repository.GetAll<Journal>().OrderBy(x => x.VoucherNo).Last().VoucherNo;
journal.VoucherNo = (int.Parse(lastvoucherno) + 1).ToString();
journal.VoucherDate = System.DateTime.Now;
journal.JournalEntries = new List<JournalEntry>();
journal.Accounts = Repository.GetAll<Ledger>();
return PartialView(journal);
}
var journal1 = Repository.Get<Journal>(id);
journal1.JournalEntries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == id);
journal1.Accounts = Repository.GetAll<Ledger>();
return PartialView(journal1);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Journal journal)
{
if (journal.Id == new Guid())
{
var jj = Repository.Save(journal);
foreach (var journalentry in journal.JournalEntries)
{
journalentry.Id = jj.Id;
Repository.Save(journalentry);
}
}
else
{
Journal jr = Repository.Get<Journal>(journal.Id);
var entries = Repository.GetAll<JournalEntry>(x=>x.Journal.Id == journal.Id);
foreach (var entry in entries)
{
Repository.Delete(entry);
}
var jj = Repository.Save(journal);
foreach (var journalentry in journal.JournalEntries)
{
journalentry.Id = jj.Id;
Repository.Save(journalentry);
}
}
return RedirectToAction("Index");
}
public ActionResult Index1()
{
Journal journal1 = Repository.Get<Journal>(new Guid("7A6EEBBC-2F3A-4A27-ACF8-A1D40115A68F"));
journal1.JournalEntries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == journal1.Id);
journal1.Accounts = Repository.GetAll<Ledger>();
return View(journal1);
}
public ActionResult Delete(Guid id)
{
Journal jr = Repository.Get<Journal>(id);
var entries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == jr.Id);
foreach (var entry in entries)
{
Repository.Delete(entry);
}
var result = Repository.Delete(jr);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Create1(Journal journal)
{
var temp = journal;
return RedirectToAction("Create",journal.Id);
}
}
}
Views are not genereted from models. You need Controller Action method to pass your model to View.
public ActionResult()
{
var model = new Journal
{
//**define here value of model's properties, that you need in View
}
return View(model);
}
EDITED: After your addition.
I would devide it into two parts. Create ViewModel and pass it from View To Controller.
public JurnalViewModel
{
public Journal journal {get; set;}
public IList<JournalEntry> JournalEntries {get; set;}
}
Than in Create action first create journal and after foreach JournalEntries in model create new JournalEntry.
EDITED 2 To your comment. Quick sample:
[HttpPost]
public ActionResult Create (JurnalViewModel model)
{
var journal = new Journal();
db.Journals.Add(journal);
journal.name = model.journal.name
.....
//**some code
db.SaveChanges()
foreach(var item in model.JournalEntries )
{
var entry = new JournalEntry()
db.JournalEntries .Add(entry);
entry.property = item.property;
....
//**some code
db.SaveChanges()
}
}
Your problem is that you have no class constructor for JournalEntries.
public Journal()
{
JournalEntries = new List<JournalEntry>();
Accounts = new List<Ledger>();
}
Right click to your Action method inside controller and click add view then check create strongly typed-view checkbox then choose your desired model from dropdown in displayed dialogue box
i have an outerViewModel and inside of it two ViewModels,
when i try to bind innermodel i get null for all the properties...
here is the code:
**Models.cs**
public class OuterModel
{
public FirstInnerModel firstInnerModel;
public SecondInnerModel secondInnerModel;
}
public class FirstInnerModel
{
public string Title;
}
public class SecondInnerModel
{
public string Title;
}
Index.cshtml
#using (Html.BeginForm("ActivateFirst", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.firstInnerModel.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.firstInnerModel.Title)
#Html.ValidationMessageFor(model => model.firstInnerModel.Title)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
HomeController.cs
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
var model = new OuterModel()
{
firstInnerModel = new FirstInnerModel(),
secondInnerModel = new SecondInnerModel()
};
return View(model);
}
[HttpPost]
public void ActivateFirst(FirstInnerModel ggg)
{
}
ggg.Title returns null...
Anyone? help!
When you submit the form it will be posting the OuterModel to the controller so you would need to do something like:
[HttpPost]
public void ActivateFirst(OuterModel ggg)
{
var whatever = ggg.FirstInnerModel.Title;
}