The parameters dictionary contains a null entry for parameter 'messageId' MVC - asp.net-mvc

This error appears when I'm training to post reply message and insert it in Replies Table using message id , I think the problem from the View when the id is calling
#using (Html.BeginForm("ReplyMessage", "Messages", FormMethod.Post, new
{ id = "form-reply-message", messageId = #ViewBag.MessageId }))
Any idea what I should change
Controller Get Method:
public ActionResult ReplyMessage(int? Id, int? page)
{
MessageReplyViewModel vm = new MessageReplyViewModel();
if (Id != null)
{
var replies = dbContext.Replies.Where(x => x.MessageId == Id.Value).OrderByDescending(x => x.ReplyDateTime).ToList();
if (replies != null)
{
foreach (var rep in replies)
{
MessageReplyViewModel.MessageReply reply = new MessageReplyViewModel.MessageReply();
reply.MessageId = rep.MessageId;
reply.Id = rep.Id;
reply.ReplyMessage = rep.ReplyMessage;
reply.ReplyDateTime = rep.ReplyDateTime;
reply.MessageDetails = dbContext.Messages.Where(x => x.Id == rep.MessageId).Select(s => s.MessageToPost).FirstOrDefault();
reply.ReplyFrom = rep.ReplyFrom;
vm.Replies.Add(reply);
}
}
else
{
vm.Replies.Add(null);
}
ViewBag.MessageId = Id.Value;
}
return View(vm);
Controller PostMethod :
[HttpPost]
[Authorize]
public ActionResult ReplyMessage(MessageReplyViewModel vm, int messageId)
{
if (vm.Reply.ReplyMessage != null)
{
Models.Reply _reply = new Models.Reply();
_reply.ReplyDateTime = DateTime.Now;
_reply.MessageId = messageId;
_reply.ReplyMessage = vm.Reply.ReplyMessage;
dbContext.Replies.Add(_reply);
dbContext.SaveChanges();
}
return RedirectToAction("Index", "Message");
View :
#using (Html.BeginForm("ReplyMessage", "Messages", FormMethod.Post, new { id = "form-reply-message", messageId = #ViewBag.MessageId }))
{
if (!ViewData.ModelState.IsValid)
{
#Html.ValidationSummary(true)
}
#Html.HiddenFor(model => model.Reply.MessageId);
#Html.TextAreaFor(p => p.Reply.ReplyMessage, new { #rows = 2, #class = "form-control" })
#Html.ValidationMessageFor(model => model.Reply.ReplyMessage)
<input type="submit" class="btn btn-primary btn-success" value="Reply" id="btn-reply-message">
}

You may have to bind it using [FromQuery] attribute here:
public ActionResult ReplyMessage(MessageReplyViewModel vm, [FromQuery("messageId")] int messageId)
{
........
}
This attributes reads the values after the "?" operator in the URL. Hopefully it will help!

Related

DropDownListFor Razor with List<string>

using (Html.BeginForm("Add", "Test", new { profil = Model.SelectedProfil }, FormMethod.Post))
{
#Html.DropDownListFor(m => m.SelectedProfil, new SelectList(Model.Profils.Select(x => new { Value = x, Text = x }),"Value","Text"))
<button type="submit">Add</button>
}
Profils = List of string
SelectedProfil = string
SelectedProfil is always null to the controller on post
Simply
using (Html.BeginForm("Add", "Test", FormMethod.Post))
#Html.DropDownList("profil", new SelectList(Model.Profils.Select(x => new { Value = x, Text = x }),"Value","Text")))
[HttpPost]
public ActionResult Add(string profil)
{
....
}

How to compare viewbag value with model another value in mvc 4

I am trying to send viewbag from action method to view. When first page loads viewbag value will be null. when I call CheckPermissions action method viewbag gets some value and it will return the same view that time viewbag contains some value and now I want to compare viewbag value with another value. I tried but following error appearing. Cannot perform runtime binding on a null reference.
This is my Index view code.
#model c3card.Models.GroupPermissionVM
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm())
{
#Html.LabelFor(m=>m.GroupID)
#Html.DropDownListFor(m => m.GroupID, Model.GroupList, "Please select", new { id = "ddlgrp" })
foreach(var permission in Model.Permissions)
{
if (ViewBag.marlid.equals(permission))
{
<label>
#Html.RadioButtonFor(m => m.perm_id, permission.perm_id, new {#checked="true"})
<span>#permission.perm_levelname</span>
</label>
}
else
{
<label>
#Html.RadioButtonFor(m => m.perm_id, permission.perm_id)
<span>#permission.perm_levelname</span>
</label>
}
}
This is my action method
public ActionResult CheckPermissions(int id)
{
var groups = db.tm_grp_group.Where(a => a.grp_isactive == true);
var permissions = db.tm_perm_level;
GroupPermissionVM model = new GroupPermissionVM
{
marlid=db.ts_grp_perm_mapping.Select(p=>p.grp_id==id).Count(),
GroupList = new SelectList(groups, "grp_id", "grp_name"),
Permissions = permissions.Select(p => new PermissionVM
{
perm_id = p.perm_id,
perm_levelname = p.perm_levelname
})
};
ViewBag.marlid = db.ts_grp_perm_mapping.Select(p => p.grp_id == id).Count();
return View("Index",model);
}
Any suggestion why I am not able to compare values inside if condition? Thanks in advance. This line causing me error if (ViewBag.marlid.equals(permission))
I edited as follows
foreach(var permission in Model.Permissions)
{
if(Model.marlid==permission.perm_id)
{
<label>
#Html.RadioButtonFor(m => m.perm_id, permission.perm_id,new { #checked = true } )#Model.marlid.ToString()
<span>#permission.perm_levelname</span>
</label>
}
You can change the code given below
if(ViewBag.marlid != null && Model.Permissions != null)
{
foreach(var permission in Model.Permissions)
{
if(ViewBag.marlid == permission.perm_id)
{
<label>
#Html.RadioButtonFor(m => m.perm_id, permission.perm_id,new { #checked = true } )#Model.marlid.ToString()
<span>#permission.perm_levelname</span>
</label>
}
}
}
Hope this helps.

Validation Message MVC

My code is as followed and the error message are not displayed:
Index.cshtml
#model WebApp.Models.OrderItems
#using (Html.BeginForm("SaveToDB", "Home", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
#Html.Partial("Information")
}
Partial : Information.cshtml
#model WebApp.Models.OrderItems
<div class="col-lg-4">
<div class="form-group">
<label for="input1" class="col-lg-4 control-label">#Html.LabelFor(model => model.CLInfo.ClientName)</label>
#Html.EditorFor(model => model.CLInfo.ClientName, new { style = "width:250px" })
#Html.ValidationMessageFor(model => model.CLInfo.ClientName)
</div>
</div>
Model :
public class OrderItems
{
public InfoCLInfo{ get; set; }
}
Model : the class for Infos
public class Info
{
[Display(Name = "Client Name")]
[Required]
public string ClientName{ get; set; }
}
The controller
[HttpPost]
[MultipleButton(Name = "action", Argument = "SaveToDB")]
public ActionResult SaveToDB(OrderItems Client)
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
if (_db == null)
_db = new OrderDB();
OrderItems ClientOrig = Session["Clientobj"] as OrderItems;
ClientOrig.CLInfo = Client.CLInfo;
Session["Clientobj"] = null;
}
return RedirectToAction("Index", "Home");
}
[Authorize]
public ActionResult Index (OrderItems Client)
{
int ClientID = Convert.ToInt32(Session["Client"]);
if ClientID == 0)
{
ClientID = 2;
Session["Client"] = ClientID;
}
if (Session["Clientobj"] == null)
{
Client = new OrderItems();
Client.CLOrderID = 123;
Session["Clientobj"] = Client;
}
else
{
Client = Session["Clientobj"] as OrderItems
}
return View(Client);
}
on post the ModelState.IsValid return false which true, but I don't have any message to tell the user where is the error to be fixed.
I tried to add : #Html.ValidationSummary(true) after the BeginForm , but it didn
Any idea please
Thanks
You cannot use RedirectToAction if you want to retain your model state. All errors and what not are kept in the ModelState object, and when you redirect to action it's performing a new get action, which starts fresh with a clean slate.
You need to return the view like you do in the original action.

MVC Model in the View not Updating

I've got a very basic MVC project that does maths operations (+ - / *) of 2 numbers
for some reasons my view is not updating after postback
here is my controller
namespace MathsAppMVC.Controllers
{
public class HomeController : Controller
{
MathsServiceClient loClient = new MathsServiceClient();
Int32 loNum1 = 0;
Int32 loNum2 = 0;
//Int32 result = 0;
String locOperation = "Add";
public ActionResult Index()
{
var model = new MathsModel
{
Number1 = loNum1,
Number2 = loNum2,
//Result = result,
MathsOperation = locOperation
};
return View(model);
}
[HttpGet]
public ActionResult MathsOperation()
{
return View();
}
[HttpPost]
public ActionResult MathsOperation(MathsModel mathsModel)
{
loNum1 = mathsModel.Number1;
loNum2 = mathsModel.Number2;
locOperation = mathsModel.MathsOperation;
if (locOperation == "Add")
{
mathsModel.Result = loClient.add(loNum1, loNum2);
}
else if (locOperation == "Subtract")
{
mathsModel.Result = loClient.subtract(loNum1, loNum2);
}
else if (locOperation == "Multiple")
{
mathsModel.Result = loClient.multiple(loNum1, loNum2);
}
else
if (locOperation == "Divide")
{
mathsModel.Result = loClient.divide(loNum1, loNum2);
}
if (ModelState.IsValid)
{
return View("Index", mathsModel);
}
else
{
return View("Index");
}
}
}
}
HERE IS VIEW
#model MathsAppMVC.Models.MathsModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("MathsOperation", "Home", FormMethod.Post, new { }))
{
<fieldset>
<legend>Maths:</legend>
<div>#Html.LabelFor(u=>u.MathsOperation)</div>
<div>#Html.DropDownListFor(u => u.MathsOperation, new SelectList(
new List<Object>
{
new { value = "Add" , text = "Add" },
new { value = "Subtract" , text = "Subtract" },
new { value = "Multiple" , text = "Multiple"},
new { value = "Divide" , text = "Divide"}
},
"value",
"text",
0))
</div>
<div>#Html.LabelFor(u=>u.Number1)</div>
<div>#Html.TextBoxFor(u=>u.Number1)</div>
<div>#Html.LabelFor(u=>u.Number2)</div>
<div>#Html.TextBoxFor(u=>u.Number2)</div>
<div>#Html.LabelFor(u=>u.Result)</div>
<div>#Html.DisplayTextFor(u=>u.Result)</div>
<input type="submit" value ="Calculate" />
<input type="reset" value ="Clear" />
</fieldset>
}
In the view after postback for what ever reason the Result is always 0.
Some one please help?
I hate to post this as an answer, but that's all I can do with my amount of reputation. I literally copied and pasted your code into a new MVC project and it works fine. Can you post your MathsServiceClient code?

using a view for multiple controller Actions, return to initial view

I have a view which displays a list of items, I'm planning on using Actions with the View (the view is the same, just different data is displayed)
I'm using a dialog to do the addedit (this works fine) I will be using the same dialog throughout.
My query is best demonstrated in the below example...
Equipment View
ActionResult PCs()...
ACtionResult Laptops()...
so under the PCs controller I hit edit and modify the data, when I update the data, I'm returned back... I want to get returned back to the action I started with
so if I edit a pc, on update, the dialog returns me back to the pcs, if I edit a laptop I go back to laptops.
I was thinking I need to pass another variable through to the addeditview to show which controller referred me.
does the above make sense, can anyone offer the best way to achieve this?
EDIT: Adding current code
I can't think how do to it at the moment, I thought id set the mode under users, and retrieve the mode, in the addedit get, but am not sure how to send mode to the add edit get
can I do it in the below somewhere?
#Html.ActionLink("Edit", "AddEditRecord", new { id = item.ID }, new { #class = "editDialog" })
#####Controller
// GET: /Users
public ActionResult Users()
{
ViewBag.Title = "User Equipment";
ViewBag.Mode = "Users";
string[] arrItems = new string[] { "Laptop", "Workstation", "Mobile","Monitor","Other Peripheral","Home Printer","Home Router","Removable Device" };
var tblequipments = from d in db.tblEquipments.Include(t => t.User).Include(t => t.ChangeLog).AsEnumerable()
where (arrItems.Contains(d.AssetType)) &&
(d.Deleted != 1 || d.Deleted == null) &&
(d.Stock != 1 || d.Stock == null) &&
(d.DecommissionDate == Convert.ToDateTime("1900-01-01") || d.DecommissionDate == Convert.ToDateTime("0001-01-01") || d.DecommissionDate == null)
select d;
return View("Equipment",tblequipments.ToList());
}
//GET: /AddEdit
[HttpGet]
public ActionResult AddEditRecord(int? id,string mode)
{
ViewBag.Mode = mode;
if (Request.IsAjaxRequest())
{
if (id != null)
{
ViewBag.IsUpdate = true;
tblEquipment Equipment = db.tblEquipments.Where(m => m.ID == id).FirstOrDefault();
return PartialView("_AddEdit", Equipment);
}
ViewBag.IsUpdate = false;
return PartialView("_AddEdit");
}
else
{
if (id != null)
{
ViewBag.IsUpdate = true;
tblEquipment Equipment = db.tblEquipments.Where(m => m.ID == id).FirstOrDefault();
return PartialView("AddEdit", Equipment);
}
ViewBag.IsUpdate = false;
return PartialView("AddEdit");
}
}
[HttpPost]
public ActionResult AddEditRecord(tblEquipment Equipment, string cmd)
{
if (ModelState.IsValid)
{
switch (cmd)
{
case "Add":
try
{
db.tblEquipments.Add(Equipment);
db.SaveChanges();
return RedirectToAction("Index");
}
catch { }
break;
case "Update":
try
{
tblEquipment Item = db.tblEquipments.Where(m => m.ID == Equipment.ID).FirstOrDefault();
if (Item != null)
{
Item.AssetNo = Equipment.AssetNo;
Item.MachineName = Equipment.MachineName;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch { }
break;
}
}
if (Request.IsAjaxRequest())
{
return PartialView("_AddEdit", Equipment);
}
else
{
return View("AddEdit", Equipment);
}
}
ADD Edit Modal View
#using (Ajax.BeginForm("AddEditRecord", "Equipment", new AjaxOptions { HttpMethod = "POST",OnSuccess = "onSuccess()", LoadingElementId = "dvLoading" }))
{
#Html.ValidationSummary(true)
<div id="equipmentDialog">
<fieldset>
<legend>Product</legend>
#if (ViewBag.IsUpdate == true)
{
#Html.HiddenFor(model => model.ID)
}
<div class="editor-label">
#Html.LabelFor(model => model.MachineName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MachineName)
#Html.ValidationMessageFor(model => model.MachineName)
sorted!
1.I added a viewbag action
2.Used that viewbag in the querystring for edit
3.put the querystring in a hiddenfield
4.got the fieldvalue on form post and redirect to action of the field value
Thanks for the help

Resources