Telerik ASP.NET Grid Column Template Issues - asp.net-mvc

I want to put a link in my Telerik grid that will call an Edit action in my Contact controller. The code that I have puts the link in its respective place but gives me a 400 Bad Request Error. I have a feeling that there is a problem with the syntax behind my columns.Template code.
Here is the Index view
columns.Template(
#<text>
#Html.ActionLink("Edit", "Edit", new { id = item.ContactId })
</text>
).ClientTemplate(#"View");
Here is the ContactController
// GET: Client/Edit/5
public ActionResult Edit(int? id)
{
using (var provosity = new ProvosityContext())
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
Contact contact = provosity.Contacts.Find(id);
if (contact == null)
return HttpNotFound();
return View(contact);
}
}
// POST: Client/Edit/5
[HttpPost]
public ActionResult Edit(Contact contact)
{
try
{
using (var provosity = new ProvosityContext())
if (ModelState.IsValid)
{
provosity.Entry(contact).State=System.Data.Entity.EntityState.Modified;
provosity.SaveChanges();
return RedirectToAction("Index");
}
return View(contact);
}
catch
{
return View();
}
}
}
}

Here goes like i do:
c.Bound(p => p.ContactId).ClientTemplate("View");

Related

MVC Form DropDownListFor

In my view I am building a form where the user select a country from a list of Countries.I get this error about Object reference not set to an instance of an object. Is there anything I am missing?
#Html.DropDownListFor(
x => x.selectedCountryId,
new SelectList(Model.ListOfCountries, "Value", "Text"),
"-- please select a Country--",
new { id = "ddlCountry", #class = "form-control" }
)
#Html.ValidationMessageFor(x => x.selectedCountryId)
Model
[Required]
public int? selectedCountryId{ get; set; }
Error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Web.Mvc.WebViewPage<TModel>.Model.get returned null.
Action Method
public ActionResult Create(RequestFormViewModel model)
{
if (!ModelState.IsValid)
{
}
return View(TemplateName, "");
public ActionResult Index()
{
RequestFormViewModel result = new RequestFormViewModel ();
try
{
var FormInfo = GetFormInfo();
if (FormInfo != null)
{
result = FormInfo;
}
}
catch (Exception e)
{
}
return View(TemplateName, result);
}
Your action methods should be like below
[HttpGet]
public IActionResult Create()
{
//Way 1
RequestFormViewModel model = new RequestFormViewModel();
model.ListOfCountries = //Select from DB or Whatever
return View(model);
//Way 2
ViewBag.ListOfCountries = //Select from DB or Whatever
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(RequestFormViewModel model)
{
if (ModelState.IsValid)
{
}
return View(model);
}
and for view if you will use way 1 so you need to add ListOfCountries as [NotMapped] to your model or create Dto for this view
for way2 you need to bind dropdown from ViewBag instead of using ListOfCountries as a property

How to insert Last Logged In time in sql and show it to next login in ASP.NET MVC 4?

I am using custom Login for my application. I want to insert last login date and time in database and show last login date and time when user login into application.
Controller Code:
public class HomeController : Controller
{
MyDatabaseEntities db = new MyDatabaseEntities();
//
// GET: /Home/
public ActionResult Index()
{
if(Session["LoggedUserID"]!= null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Login l)
{
if (ModelState.IsValid)
{
using(MyDatabaseEntities db = new MyDatabaseEntities())
{
this.UpdateLoginLastUpdateStatus();
var v = db.Logins.Where(a => a.UserName.Equals(l.UserName) && a.Password.Equals(l.Password)).FirstOrDefault();
if (v!= null)
{
Session["LoggedUserID"] = v.UserID.ToString();
Session["LoggeduserName"] = v.UserName.ToString();
Session["LastLogin"] = v.LastWebLogin.ToString();
return RedirectToAction("Index");
}
}
}
if(!ModelState.IsValid)
{
ModelState.AddModelError("","Username or Password is incorrect!!");
}
return View(l);
}
public void UpdateLoginLastUpdateStatus()
{
Login l = new Login();
l.LastWebLogin = DateTime.Now.ToString();
db.SaveChanges();
}
[HttpGet]
public ActionResult LogOff()
{
Session.Abandon();
return RedirectToAction("Login", "Home");
}
}
}
Index View
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#if (Convert.ToString(Session["LoggedUserID"]) != "")
{
<section>
<p class="toplink">#Html.ActionLink("Logout", "LogOff", "Home")</p>
</section>
}
Last Logged on: #Session["LastLogin"]
You have been logged in.
I am able to Log In and Log Out but this Last Logged In Time is not working.
The problem is this line is trying to update the login LastWebLogin before you've even retrieved it:
this.UpdateLoginLastUpdateStatus();
You need to call this AFTER you've assigned the Login to the variable v. Additionally, the method is creating a NEW Login class, not using an existing one. For that to work you'd have to pass a parameter v to the method. You don't even need that method really - unless you call it from multiple places and you want to avoid repeated code - it just needs to be a simple as:
var v = db.Logins.Where(a => a.UserName.Equals(l.UserName) && a.Password.Equals(l.Password)).FirstOrDefault();
if (v!= null)
{
// get previous login
var prevLogin = v.LastWebLogin;
// update with current login
v.LastWebLogin = DateTime.Now.ToString();
db.SaveChanges();
Session["LoggedUserID"] = v.UserID.ToString();
... etc

Data not displaying without model null check..Why?

I am using MVC4 Razor
Controller--
[HttpPost]
public ActionResult FillLogin(LoginModel model)
{
if (ModelState.IsValid)
{
if (model.username == "password")
{
string x = model.getdata();
model.field1= "Hello";
return View(model);
}
}
return View(model);
}
In view i am not getting the Data Displayed when i tried like
#Html.TextBoxFor(m => m.field1)
But working Fine if Given like
#if (Model != null )
{
#Html.TextBoxFor(m => m.field1)
}
Can anyone help me why this happens....I am new to MVC
Model should never be null. And I suspect that the problem is in the GET action not in the POST one. ALWAYS return a new instance of the model
public ActionResult FillLogin()
{
return View(new LoginModel());
}

MVC EditorForModel Freeman

I'm reading a book Pro ASP.NET MVC3 Framework - Freeman Sandersan where it's shown how to make simple administration im web shop.
The problem is when I try to save changes of one product it does not save.
Edit view:
#using (Html.BeginForm()) {
#Html.EditorForModel()
<input type="submit" value="Save" />}
Edit method:
[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
repository.SaveProduct(product);
TempData["message"] = string.Format("{0} has been saved", product.Name);
return RedirectToAction("Index");
}
// there is something wrong with the data values
return View(product);
}
Save product method:
private EFDbContext context=new EFDbContext();
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
context.SaveChanges();
}
Results of editing: I change the name of the product to "Kayakkkkkkkkkk". Temp message says that saving completed but the name of product is still "Kayak".
Solved.
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
else
{
context.Products.Attach(product);
context.Entry(product).State = EntityState.Modified;
}
context.SaveChanges();
}

Multiple Forms in same page ASP.net MVC

I working on my first ASP.net MVC project and and i got some problems using multi forms in same page.
First i have created 2 partial Class :
(*Register will allow user to register,
*Login it allow user to login.)
Then i used HTML.render to integrate them in my "Logpage".
So i have To uses 2 different Action. Like this one:
[HttpPost]
public ActionResult Login(LogModel.Login Model)
{
if (ModelState.IsValid)
{
if (LogModel.Login.Verifuser(Model.IDUser, Model.Password))
{
FormsAuthentication.SetAuthCookie(Model.IDUser, false);
if (LogModel.Login.IsAdmin(Model.IDUser, Model.Password))
{
return View("Admin/Index");
}
else
{
return View("Agence/Index");
}
}
else
{
ModelState.AddModelError("", "Invalide username or Password");
return View(Model);
}
}
return View(Model);
}
The problem that on error case i'm redirect to new Page(White page contain validation summary). So i'm wondring how to show this error message in my default page Logpage.
You can solve this with three actions and a complex model.
public class LoginOrRegisterViewModel
{
public Models.RegisterViewModel Register { get; set; }
public Models.LoginViewModel Login { get; set; }
}
[HttpGet]
public ActionResult Login()
{
return View("Login", new LoginOrRegisterViewModel());
}
[HttpPost]
public ActionResult Register(Models.LoginViewModel model)
{
if(!ModelState.IsValid)
return View("Login", new LoginOrRegisterViewModel(){ Register = model });
else
{
//TODO: Validate the user
//TODO: Write a FormsAuth ticket
//TODO: Redirect to somewhere
}
}
[HttpPost]
public ActionResult Login(Models.RegistrationViewModel model)
{
if(!ModelState.IsValid)
return View("Login", new LoginOrRegisterViewModel(){ Login = model});
else
{
//TODO: CRUD for registering user
//TODO: Write forms auth ticket
//TODO: Redirect
}
}
In your code, make sure that you set the action of the Form:
#model Models.LoginOrRegisterViewModel
#using(Html.BeginForm("Login", "Controller", FormMethod.Post, new { id = "loginForm"}))
{
#Html.EditorFor(m => Model.Login)
}
#using(Html.BeginForm("Register", "Controller", FormMethod.Post, new { id = "registerForm"}))
{
#Html.EditorFor(m => Model.Register)
}
It looks like you also need to call IsAdmin in the !Verifyuser branch, to have it return the correct view:
if (ModelState.IsValid)
{
if (LogModel.Login.Verifuser(Model.IDUser, Model.Password))
{
FormsAuthentication.SetAuthCookie(Model.IDUser, false);
if (LogModel.Login.IsAdmin(Model.IDUser, Model.Password))
{
return View("Admin/Index");
}
else
{
return View("Agence/Index");
}
}
else
{
ModelState.AddModelError("", "Invalide username or Password");
if (LogModel.Login.IsAdmin(Model.IDUser, Model.Password))
return View("Admin/Index", Model);
else
return View("Agence/Index", Model);
}
}
Currently, you're calling return View(Model); when you have a ModelState error, which returns the default view for the action, called "Login".
If you want multiple forms posted to a controller action simultaneously, create a JSON object with client JS that has a separate property for each form and give each of those properties a camel-case name that corresponds to a respective ProperCase parameter of your controller action. Then, send in a serialization of that JSON object to your controller:
let form1 = $('#my-form1-id');
let form2 = $('#my-form2-id');
let url = 'myArea/myController/myAction'
let viewData = {
controllerParameter1: form1,
controllerParameter2: form2
};
$.ajax({
url: url,
type: 'POST',
data: JSON.stringify(viewData),
dataType: "json",
beforeSend: function () {
$('#my-submit-button-id').html('<i class="fa fa-2x fa-cog fa-spin"></i>');
$('#my-submit-button-id').attr("disabled", "disabled");
},
success: function (res) {
alert("Submitted!");
},
error: function (status, err) {
alert("Failed!");
},
complete: function (status, err) {
$('#my-submit-button-id').html('Submit My 2 Forms');
}
});
That should work for a controller action w/ a signature similar to:
[HttpPost]
public virtual async Task<ActionResult> MyAction(ViewModel1 controllerParameter1, ViewModel2 controllerParameter2)
{
// do amazing things
}

Resources